编译时和运行时转换c#

nan*_*nan 17 .net c# type-systems casting

我想知道为什么在编译时检查C#中的某些转换,而在其他情况下,责任转储到CLR上.如上所述都是不正确的,但以不同的方式处理.

class Base { }
class Derived : Base { }
class Other { }

static void Main(string[] args)
{
    Derived d = (Derived)new Base();     //Runtime       InvalidCastException
    Derived d = (Derived)new Other();    //Compile-time  Cannot convert type...
}
Run Code Online (Sandbox Code Playgroud)

在阅读"C#深度"时,我发现了有关此主题的信息,其中autor说:
"如果编译器发现实际上不能使该转换工作,它将触发编译错误 - 如果理论上允许但实际上在执行时不正确,CLR会抛出异常."

"理论上"是否意味着通过继承层次结构(对象之间的另一个关联性?)连接,还是编译器的内部业务?

Mar*_*ers 22

  • 可以在编译时检查向上转换 - 类型系统保证转换成功.
  • 在编译时不能(通常)检查downcast,因此总是在运行时检查它们.
  • 不相关的类型不能相互转换.

编译器仅考虑静态类型.运行时检查动态(运行时)类型.看看你的例子:

Other x = new Other();
Derived d = (Derived)x; 
Run Code Online (Sandbox Code Playgroud)

静态类型xOther.这与Derived编译时失败无关.

Base x = new Base();
Derived d = (Derived)x; 
Run Code Online (Sandbox Code Playgroud)

x现在是静态类型Base.类型Base 可能具有动态类型Derived,因此这是一个向下倾斜.一般来说编译器不能从静态类型的知道x,如果它运行时类型Base,Derived,其他一些子类Base.因此,是否允许转换的决定留给运行时.