为什么,对“必须继承自 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>
吗?