C#类型转换错误,尽管通用约束
为什么,对于类P的类型参数T的“必须从Ainheritance”的通用约束,第一次调用成功但第二次调用失败并且注释中详细说明了类型转换错误:
abstract class A { } static class S { public static void DoFirst(A argument) { } public static void DoSecond(ICollection argument) { } } static class P where T : A, new() { static void Do() { S.DoFirst(new T()); // this call is OK S.DoSecond(new List()); // this call won't compile with: /* cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.ICollection' */ } }
这是C#在generics类型上缺乏协方差的一个例子(C# 确实支持数组协方差)。 C#4将在接口类型上添加此function,并且还将更新多个BCL接口类型以支持它。
请参阅C#4.0:协方差和逆变 :
在本文中,我将尝试介绍一种C#4.0创新。 其中一个新function是类型参数的协方差和逆变,现在由通用委托和通用接口支持。 首先让我们看看这些词是什么意思:)
约束对问题没有影响; 问题是你在一个需要ICollection的参数中传递List – C#不支持协方差,所以你需要显式地将列表转换为ICollection:
S.DoSecond((ICollection) new List()); // this call will be happy