因为它可能无效.考虑一下:
class Base { }
class A : Base { }
class B : Base { }
A temp1 = new A();
B temp2 = (B)temp1; // not valid
Run Code Online (Sandbox Code Playgroud)
仅仅因为它们共享相同的基类并不意味着你可以将一个类型转换为另一个.
请注意,您可以使用as运算符来解决此问题:
var result = objectOfTypeT as U; // this does not give any compilation error
// but will result in a null reference if
// objectOfTypeT cannot be converted to U
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
926 次 |
| 最近记录: |