我想知道为什么在编译时检查 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...
}
在阅读“深入 C#”时,我发现有关此主题的信息,其中 autor 说:
“如果编译器发现该强制转换实际上不可能工作,它将触发编译错误 - 如果理论上允许但实际上在执行时不正确,CLR 将抛出异常。”
“理论上”是指通过继承层次结构连接(对象之间的另一种亲和力?)还是编译器的内部业务?