在C#3.5中向下转换泛型类型

the*_*row 4 .net c# generics downcast

为什么我只能转发一个通用而不是垂头丧气呢?
如果我的约束表明where T : BaseClass并且U是从BaseClass派生的,那么编译器如何不清楚(U)objectOfTypeT

Fre*_*örk 5

因为它可能无效.考虑一下:

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)