C# Cannot convert from IEnumerable<Base> to IEnumerable<Derived>

◇◆丶佛笑我妖孽 提交于 2019-12-19 07:39:09

问题


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.

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
    }
}

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, 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...?


回答1:


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).

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.




回答2:


In C# 3.0 you can use the "Cast" extension method. If you import System.Linq and then use this code:

public void AddRange2<T>(IEnumerable<T> foos) where T : Foo
{
    m_Foos.AddRange (foos.Cast<Foo>());
}

Then it should work for you.




回答3:


There is workaround with extension method:

public static IEnumerable<TBase> ToBaseEnumerable<TBase, TDerived>( this IEnumerable<TDerived> items ) where TDerived : TBase {
    foreach( var item in items ) {
        yield return item;
    }
}
...
IEnumerable<Employee> employees = GetEmployees(); //Emplyoee derives from Person
DoSomethingWithPersons( employees.ToBaseEnumerable<Person, Employee>() );

but the "<Person, Employee>" is little bit awkward :/.




回答4:


The cast solution of course might generated class cast exceptions. The person who posted the enumerable extension work around said it was awkward. I came up with a solution which is only half as awkward, don't know if I'll use it:

public static class UpTo<T>
{
    public static IEnumerable<T> From<F>(IEnumerable<F> source) where F:T
    {
        // this cast is guaranteed to work
        return source.Select(f => (T) f);
    }
}

Usage:

IEnumerable mammals = UpTo<Mammal>.From(kennel.Dogs)



来源:https://stackoverflow.com/questions/634268/c-sharp-cannot-convert-from-ienumerablebase-to-ienumerablederived

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!