我想知道为什么在编译时检查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会抛出异常."
"理论上"是否意味着通过继承层次结构(对象之间的另一个关联性?)连接,还是编译器的内部业务?