可能重复:
Compile-time and runtime casting c#为什么不C#编译器赶上一个InvalidCastException
据我了解,下面的代码将总是编译,并且将另外总是通过投掷InvalidCastException
在运行时失败。
例子:
public class Post { }
public class Question : Post { }
public class Answer : Post
{
public void Fail()
{
Post p = new Post();
Question q = (Question)p; // This will throw an InvalidCastException
}
}
我的问题是...
- 如果我的假设是关闭,然后有人可以提供一个例子演示一下怎么了?
- 如果我的假设是正确的,那么编译器为什么不警告这个错误?
为什么你期望编译器遵循所有可能的代码路径来确定'p '在演员演出之前没有改变过? –
如果事件没有改变,Post可以实现一个隐式操作符来将自己投射到Question上,反之亦然。 – PVitt
演员是牛仔,上公牛和骑宝宝 – kenny