无法传递列表< Foo>到预期List< IFoo>的方法,其中Foo:IFoo [英] Cannot pass a List<Foo> to a method expecting a List<IFoo>, where Foo : IFoo
问题描述
我有一个实现 IFoo
界面的类 Foo
。我有一个方法以 List< IFoo>
作为参数。然而,它不能从 List< Foo>
转换为 List< IFoo>
- 这令我惊讶,因为 Foo
实现 IFoo
界面。
我该如何解决这个问题,为什么会发生这种情况? (总是从错误中学习)
这是因为 List< T>
不是协变的。有关详细信息,请参见 C#中的协变和反变量。
如果你可以让你的方法在 原因 I have a class How can I get around this, and why does this occur? (Always good to learn from mistakes) This is because If you can make your method work on The reason 这篇关于无法传递列表< Foo>到预期List< IFoo>的方法,其中Foo:IFoo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! IEnumerable< T>
上工作,那么这将起作用(你可以传递因为它被定义为
IEnumerable< out T> ,因此在.NET 4中将< Foo>
列入
$ b List< T>
不是协变的,btw,是因为它是没有定义只读合约。由于 List< T>
明确允许您添加元素(通过 Add(T)
),因此不允许协变工作。如果允许这样做,该方法预计能够添加类型为 Bar
的元素(如果 Bar
从 IFoo
)列表中,但这会失败,因为列表真的 a List< Foo>
,而不是 List< IFoo>
。既然 IEnumerable< T>
只允许你迭代列表,但不能修改它,它可以是协变的并且在这种情况下按照预期工作。Foo
implementing the IFoo
interface. I have a method taking a List<IFoo>
as a parameter. However, it cannot convert from List<Foo>
to List<IFoo>
- this surprises me, since Foo
implements the IFoo
interface. List<T>
is not covariant. For details, see Covariance and Contravariance in C#.IEnumerable<T>
instead, this will work (you can pass List<Foo>
into IEnumerable<IFoo>
in .NET 4, since it's defined IEnumerable<out T>
).List<T>
is not covariant, btw, is because it's not defining a read only contract. Since List<T>
explicitly allows you to add elements (via Add(T)
), it's not safe to allow covariance to work. If this was allowed, the method would expect to be able to add an element of type Bar
(if Bar
derives from IFoo
) to the list, but that would fail, since the list is really a List<Foo>
, not a List<IFoo>
. Since IEnumerable<T>
only allows you to iterate through the list, but not modify it, it can be covariant and just work as expected in this case.