这不应该是有效的 C# 代码吗?
class A<T> where T : class {
public void DoWork<K>() where K : T {
var b = new B<K>(); // <- compile time error
}
}
class B<U> where U : class {
}
编译器吐出这个错误:
error CS0452: The type 'K' must be a reference type in order to use it as parameter 'U' in the generic type or method 'ConsoleApplication1.B'
编译器难道不应该能够弄清楚 K 是类型 T 的约束还是从 T 派生的,所以它显然应该是引用类型(T 被约束为引用类型)?
最佳答案
我之前的回答不正确;我已经删除了它。感谢指出我错误的用户配置器。
Shouldn't the compiler be able to figure out that K is constraint to be of type T or derived from T so it should obviously be a reference type (T is constrained to be a reference type)?
没有。
K 被限制为类型 T 或派生自 T 的类型。T 被限制为引用类型。 这并不意味着K是引用类型。即:object是引用类型,int是从object派生的类型。如果 T 是对象,那么 K 可以是 int,它不是引用类型。
关于C# 泛型类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5041967/