当前位置 : 主页 > 编程语言 > c语言 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-25
为什么,对于“必须从A继承”的类P的类型参数T的通用约束,第一次调用成功但第二次调用失败,注释中详细说明了类型转换错误: abstract class A { }static class S{ public static void DoFirst(A argume
为什么,对于“必须从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

网友评论