为什么我只能向上转换泛型而不能向下转换?
编译器为什么不清楚如果我的约束说 where T : BaseClass
and U is derived from BaseClass that (U)objectOfTypeT
is valid?
最佳答案
因为它可能无效。考虑一下:
class Base { }
class A : Base { }
class B : Base { }
A temp1 = new A();
B temp2 = (B)temp1; // not valid
仅仅因为它们共享相同的基类并不意味着您可以将一个类型转换为另一个。
请注意,您可以使用 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
关于c# - 在 C# 3.5 中向下转换泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4007497/