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

C#类型转换错误,尽管通用约束

发布时间:2020-12-16 01:31:33 所属栏目:百科 来源:网络整理
导读:为什么,对于“必须从A继承”的类P的类型参数T的通用约束,第一次调用成功但第二次调用失败,注释中详细说明了类型转换错误: abstract class A { }static class S{ public static void DoFirst(A argument) { } public static void DoSecond(ICollectionA argu
为什么,对于“必须从A继承”的类P的类型参数T的通用约束,第一次调用成功但第二次调用失败,注释中详细说明了类型转换错误:

abstract class A { }

static class S
{
    public static void DoFirst(A argument) { }
    public static void DoSecond(ICollection<A> argument) { }
}

static class P<T>
    where T : A,new()
{
    static void Do()
    {
        S.DoFirst(new T());             // this call is OK

        S.DoSecond(new List<T>());      // this call won't compile with:

        /* cannot convert from 'System.Collections.Generic.List<T>'
           to 'System.Collections.Generic.ICollection<A>' */
    }
}

通用约束不应该确保List< T>.确实是ICollection< A>?

解决方法

这是C#在泛型类型上缺少 covariance的一个例子(C#确实支持数组协方差). C#4将在接口类型上添加此功能,并且还将更新多个BCL接口类型以支持它.

请参阅C# 4.0: Covariance and Contravariance:

In this article I’ll try to cover one of the C# 4.0 innovations. One of the new features is covariance and contravariance on type parameters that is now supported by generic delegates and generic interfaces. First let’s see what does these words mean

(编辑:李大同)

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

    推荐文章
      热点阅读