这是在C#4协方差错误? [英] Is this a covariance bug in C# 4?
问题描述
在下面的一段code的我希望能暗中从元素投
到 baseElements
因为 TBASE
隐式转换为 IBase的
。
In the following piece of code I expected to be able to implicitly cast from elements
to baseElements
because TBase
is implicitly convertible to IBase
.
public interface IBase { }
public interface IDerived : IBase { }
public class VarianceBug
{
public void Foo<TBase>() where TBase : IBase
{
IEnumerable<TBase> elements = null;
IEnumerable<IDerived> derivedElements = null;
IEnumerable<IBase> baseElements;
// works fine
baseElements = derivedElements;
// error CS0266: Cannot implicitly convert type
// 'System.Collections.Generic.IEnumerable<TBase>' to
// 'System.Collections.Generic.IEnumerable<IBase>'.
// An explicit conversion exists (are you missing a cast?)
baseElements = elements;
}
}
不过,我得到了在评论中提到的错误。
However, I get the error that is mentioned in the comment.
从规格报价:
A型 T&LT; A1,...,一个&GT;
是方差 - 转换为一个类型 T&LT; B1,...,BN&GT;
如果 T
是一个接口或变异类型参数 T&LT; X1,...,Xn有害&GT;
,并为每个变量类型参数曦
以下情况之一成立:
A type
T<A1, …, An>
is variance-convertible to a typeT<B1, …, Bn>
ifT
is either an interface or a delegate type declared with the variant type parametersT<X1, …, Xn>
, and for each variant type parameterXi
one of the following holds:
-
曦
是协变的和隐式引用或标识转换从艾
存在碧
Xi
is covariant and an implicit reference or identity conversion exists fromAi
toBi
曦
是逆变和隐式引用或标识转换从碧
存在艾
Xi
is contravariant and an implicit reference or identity conversion exists from Bi
to Ai
曦
是不变和身份转换,从艾
存在碧
Xi
is invariant and an identity conversion exists from Ai
to Bi
检查我的code,这似乎是与规范是一致的:
Checking my code, it appears to be consistent with the spec:
-
的IEnumerable&LT;出T&GT;
是一个接口类型
的IEnumerable&LT;出T&GT;
声明与变异类型参数
T
是协变
隐式引用转换从 TBASE
存在 IBase的
所以 - 它是在C#编译器4的错误
So - is it a bug in the C# 4 compiler?
推荐答案
方差仅适用于引用类型(或出现的标识的转换)。它不知道, TBASE
是引用类型,除非添加:类
:
Variance only works for reference-types (or there is an identity conversion). It is not known that TBase
is reference type, unless you add : class
:
public void Foo<TBase>() where TBase : class, IBase
因为我可以写:
public struct Evil : IBase {}
这篇关于这是在C#4协方差错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!