这件事困扰了我一段时间。我有点难以理解为什么在以下代码中需要显式强制转换:
public static class CastStrangeness
{
public class A
{
}
public class B
: A
{
}
public static void Foo<T>(T item)
where T : A
{
// Works.
A fromTypeParameter = item;
// Does not compile without an explicit cast.
T fromConcreteType = (T)fromTypeParameter;
// Does not compile without an explicit cast.
Foo<T>((T)fromTypeParameter);
}
public static void Bar(A item)
{
// Compiles.
Foo<A>(item);
}
}
在我看来,T 一定是 A,所以编译器肯定可以推断出 A 的任何实例都一定可以分配给 T?否则,我将无法将 A 或 B 传递给 Foo()。那我错过了什么?
附言。我已经尝试搜索关键字的无尽排列,但每个结果似乎都指向协变和逆变 WRT 通用接口(interface):)
最佳答案
例如:
Foo(new B());
你的第一个作业没问题:
A fromtypeParameter = item;
因为 B : A.
但是这个赋值是不行的:
T fromConcreteType = fromTypeParameter;
因为您很可能将 fromTypeParameter 指定为:
fromTypeParameter = new A();
您显然不能将其转换为 T(在本例中为 B)。 T 比 A 更具体,它可以派生自 A。因此您可以采用一种方式而不是另一种方式,而无需显式强制转换(这可能会失败)。
关于C# 泛型 - 为什么需要从具体类型显式转换回 T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7760811/