在下面的代码中,我希望能够隐式转换elements
to baseElements
因为TBase
可以隐式转换为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;
}
}
但是,我收到评论中提到的错误。
引用规范:
A type T<A1, …, An>
可方差转换为类型T<B1, …, Bn>
if T
是使用变体类型参数声明的接口或委托类型T<X1, …, Xn>
,并且对于每个变体类型参数Xi
以下其中一项成立:
检查我的代码,它似乎与规范一致:
那么,这是 C# 4 编译器中的错误吗?
方差仅适用于引用类型(或者有一个identity转换)。不知道的是TBase
是引用类型,除非你添加: class
:
public void Foo<TBase>() where TBase : class, IBase
因为我可以写一个:
public struct Evil : IBase {}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)