如何转换一个List<接口与GT;列出<混凝土> ;?

如何转换一个List<接口与GT;列出<混凝土> ;?

问题描述:

我定义为一个接口:

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

和一个类实现该接口:

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



我然后创建一个返回的ICollection像这样一个功能:

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

无法转换类型
的对象System.Collections.Generic.List 1 [MyInterface的]'
键入
'System.Collections.Generic.IEnumerable
1 [MyClass的]。

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

例外。我在做什么错

A 列表&LT; MyInterface的&GT; 不能被转换为列表&LT; MyClass的&GT; 一般,因为第一个列表可能包含实现对象 MyInterface的但AREN 'T实际上对象类型 MyClass的

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.

然而,因为在你的情况,你知道你是怎么构建的名单,可以肯定的是它仅包含 MyClass的的对象,你可以做到这一点使用LINQ:

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