您具有以下所示的类:
public class A
{
}
public class B : A
{
}
您将基类转换为派生类的类型
A w = (B) new A();
B x = (B) new A();
这将无法在运行时起作用,因为您无法真正将基类转换为派生类。
但是why is there no compile time error
呢 为什么Visual Studio在抛出错误之前允许我达到运行时间?
有2种类型的演员
我相信(B)new A()
即使强制转换失败也(B)someObjectOfTypeA
可以在编译时允许的原因是因为可以成功,new A()
并且绝对是此类“ A类对象”之一。编译时检测可能会需要额外的基础结构,并且没有被认为是有益的(因为此强制转换在运行时立即失败,因此即使对您的代码进行最基本的测试也很少会错过)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句