如何转换一个List<接口与GT;列出<混凝土&GT ;? [英] How do I convert a List<interface> to List<concrete>?

查看:152
本文介绍了如何转换一个List<接口与GT;列出<混凝土&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 列表< MyInterface的> 不能被转换为列表< MyClass的> 一般,因为第一个列表可能包含实现对象 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);

这篇关于如何转换一个List&LT;接口与GT;列出&LT;混凝土&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆