【发布时间】:2015-04-26 04:00:38
【问题描述】:
你有这些类如下所示:
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 允许我在抛出错误之前达到运行时?
【问题讨论】:
-
这可能会有所帮助:ericlippert.com/2012/07/10/696
-
C#编译器允许
explicit从派生类转换为基类,但你必须确保没有运行时错误 -
这实际上是错误的,无论您编写显式或隐式转换,在运行时您都会收到异常,因为不允许转换为派生类。