这不应该是有效的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被约束为引用类型)?
指定type参数时将应用约束.虽然为U指定了K,但尚未为K指定类型.由于U要求其类型为引用类型,因此编译器希望确认K确实是引用类型,但它不能.因此,您需要明确说明它将是.
The specification节在第4.4.4节中说明:
For each where clause,the type argument A that corresponds to the named type parameter is checked against each constraint…
然后:
A compile-time error occurs if one or more of a type parameter’s constraints are not satisfied by the given type arguments.
Since type parameters are not inherited,constraints are never inherited either.
最后一点表明K不会继承T的约束.
更新
虽然我的结论看似正确,但我的证据有点不稳定,正如现在已删除的Eric Lippert’s response回复中所阐明的那样.在那里,Eric说明规范的正确部分是:
A type parameter is known to be a
reference type if it has the reference
type constraint or its effective base
class is not object or
System.ValueType
.