基地> C#不能自IEnumerable<转换;到了IEnumerable<衍生GT; [英] C# Cannot convert from IEnumerable<Base> to IEnumerable<Derived>
问题描述
我想的AddRange(IEnumerable的)时将列出最近遇到了麻烦。可能是一个经典的问题,但我真的不明白呢。
I recently run into trouble when trying to AddRange(IEnumerable) to a List. Probably a classic issue, but I do not really get it yet.
据我了解,期待一个列表参数的方法不满意列表,因为他们可能会增加一个基地的名单,这显然是不可能的。
I understand that methods expecting a List parameter are not satisfied with a List, because they might try to add a Base to the List, which is obviously impossible.
但是,如果我得到这个正确的,因为IEnumerables本身不能改变,它应该在这种情况下工作。
But if i get this correctly, since IEnumerables themselves cannot be changed, it ought to work in this case.
我想看起来像这样的代码:
The code i thought of looks like this:
class Foo
{
}
class Bar : Foo
{
}
class FooCol
{
private List<Foo> m_Foos = new List<Foo> ();
public void AddRange1(IEnumerable<Foo> foos)
{
m_Foos.AddRange (foos); // does work
}
public void AddRange2<T>(IEnumerable<T> foos) where T : Foo
{
m_Foos.AddRange (foos); // does not work
}
}
class Program
{
static void Main(string[] args)
{
FooCol fooCol = new FooCol ();
List<Foo> foos = new List<Foo> ();
List<Bar> bars = new List<Bar> ();
fooCol.AddRange1 (foos); // does work
fooCol.AddRange1 (bars); // does not work
fooCol.AddRange2 (foos); // does work
fooCol.AddRange2 (bars); // does work
}
}
我试图通过一个提示编译器在AddRange2方法,但是这只是转移到周围的问题。
I tried to pass a hint to the compiler in the AddRange2 method, but this just moved to problem around.
时我的思维方式存在缺陷?这是语言的限制还是设计?
Is my way of thinking flawed? Is this a limitation of the language or is it by design?
IIRC,对于这种操作的支持添加到Java 1.5,所以也许它会被添加到C#在未来的某个时刻,太...?
IIRC, support for this kind of operations was added to Java 1.5, so maybe it will be added to C# at some point in the future, too...?
推荐答案
这是协方差,并且将其固定在C#4.0 /。 NET 4.0。目前,通用的选择是最好的答案(对于的IEnumerable< T>
- 不是的IList< T>
等)
This is covariance, and will be fixed in C# 4.0 / .NET 4.0. For now, the generic option is the best answer (for IEnumerable<T>
- not IList<T>
etc).
但泛型方法中,你必须要考虑在 T
的条款。你也可以使用演员LT; T>
或 OfType< T>
使用LINQ来实现类似的东西。
But within the generic method, you have to think in terms of T
. You could also use Cast<T>
or OfType<T>
with LINQ to achieve something similar.
这篇关于基地> C#不能自IEnumerable<转换;到了IEnumerable<衍生GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!