C#泛型类型约束 [英] C# generics type constraint

查看:194
本文介绍了C#泛型类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Should't这是有效的C#代码

Should't this be valid C# code?

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 {

}



编译器吐出这个错误:

The compiler spits this error:

错误CS0452:类型'K'必须是引用类型,才能在泛型类型或方法使用它作为参数'U' ConsoleApplication1.B

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约束为引用类型)?

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)?

推荐答案

的约束应用时,类型参数中指定。 A型一直没有在K指定即使正在为U.指定K作为ü要求其类型为引用类型,编译器正在确认K是确实是一个引用类型,但它不能。因此,你需要明确指出,这将是。

The constraints are applied when the type parameter is specified. A type has not been specified for K even though K is being specified for U. As U requires its type to be a reference type, the compiler is looking to confirm that K is indeed a reference type, but it cannot. Therefore, you need to explicitly state that it will be.

规范州第4.4.4节:

对于每个where子句,对应于命名的类型参数针对每个约束......

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中的制约因素。

This last point indicates that K will not inherit the constraints from T.

更新结果
在我的结论看起来是正确的,我的证据有点不稳在从埃里克利珀的回应。在那里,埃里克表示,规范的正确的部分是:

Update
While my conclusions appear correct, my evidence is a little shaky as was clarified in a now deleted response from Eric Lippert's response. There, Eric stated that the correct part of the specification is:

一个类型参数被称为是一个
引用类型,如果它具有参考
型或约束其有效基
类不反对或
System.ValueType

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.

这篇关于C#泛型类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆