加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#泛型类型约束

发布时间:2020-12-15 19:59:44 所属栏目:百科 来源:网络整理
导读:这不应该是有效的C#代码吗? class AT where T : class { public void DoWorkK() where K : T { var b = new BK(); // - compile time error }}class BU where U : class {} 编译器吐出此错误: error CS0452: The type ‘K’ must be a reference type in o
这不应该是有效的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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读