C#类型转换错误,尽管通用约束 [英] C# Type Conversion Error Despite Generic Constraint
问题描述
为什么,对类P的类型参数T必须继承自A的泛型约束,第一次调用成功,但第二次调用失败,类型转换错误详述在注释中:
Why, with a generic constraint on type parameter T of class P of "must inherit from A", does the first call succeed but the second call fail with the type conversion error detailed in the comment:
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>
? b $ b
Shouldn't the generic constraint ensure that List<T>
is indeed ICollection<A>
?
推荐答案
这是C#缺少 支持数组协方差)的rel =nofollow noreferrer>协方差。 C#4将在接口类型上添加此功能,并且还将更新多个BCL接口类型以支持它。
This is an example of C#'s lack of covariance on generic types (C# does support array covariance). C# 4 will add this feature on interface types and also will update several BCL interface types to support it as well.
请参阅 C#4.0:协方差和对比度:
在本文中,我将尝试覆盖一个
的C#4.0创新。
新特性之一是协方差和
违反类型参数,
现在由通用委托
和通用接口支持。首先让我们
看看这些词是什么意思:)
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 :)
这篇关于C#类型转换错误,尽管通用约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!