How do I convert a List<interface> to List<concrete>?

妖精的绣舞 提交于 2019-12-30 03:38:08

问题


I have an interface defined as:

public interface MyInterface {
     object foo { get; set; };
}

and a class that implements that interface:

public class MyClass : MyInterface {
     object foo { get; set; }
}

I then create a function that returns a ICollection like so:

public ICollection<MyClass> Classes() {
    List<MyClass> value;

    List<MyInterface> list = new List<MyInterface>(
        new MyInterface[] {
            new MyClass {
                ID = 1
            },
            new MyClass {
                ID = 1
            },
            new MyClass {
                ID = 1
            }
        });

    value = new List<MyClass>((IEnumerable<MyClass>) list);

    return value;
}

It would compile but would throw a

Unable to cast object of type 'System.Collections.Generic.List1[MyInterface]' to type 'System.Collections.Generic.IEnumerable1[MyClass]'.

exception. What am I doing wrong?


回答1:


A List<MyInterface> cannot be converted to a List<MyClass> in general, because the first list might contain objects that implement MyInterface but which aren't actually objects of type MyClass.

However, since in your case you know how you constructed the list and can be sure that it contains only MyClass objects, you can do this using Linq:

return list.ConvertAll(o => (MyClass)o);



回答2:


But a List<MyInterface> is emphatically not a List<MyClass>.

Think:

interface IAnimal { }

class Cat : IAnimal { }
class Dog : IAnimal { }

var list = new List<IAnimal> { new Cat(), new Dog() };

Then

var cats = (List<Cat>)list;

Absurd!

Also,

var cats = list.Cast<Cat>();

Absurd!

Further

var cats = list.ConvertAll(x => (Cat)x);

Absurd!

Instead, you could say

var cats = list.OfType<Cat>();



回答3:


You could use Cast<> extension method:

return list.Cast<MyClass>();



回答4:


I find Automapper very useful for converting interfaces to concrete classes.



来源:https://stackoverflow.com/questions/6019765/how-do-i-convert-a-listinterface-to-listconcrete

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