IEnumerable T列出< T> [英] IEnumerable<T> to List<T>

查看:72
本文介绍了IEnumerable T列出< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我环顾四周,找不到答案。我有一个返回

Ok I have looked all around and can't find an answer. I have a method that returns an

IEnumerable<ICar> 

,并且调用方法将方法的结果存储在

and the calling method is storing the results of the method in

List<ICar> 

但出现以下错误。

System.Collections.Generic.IEnumerable<Test.Interfaces.ICar> to 
System.Collections.Generic.List<Test.Interfaces.ICar>. An explicit conversion exists   
(are you missing a cast?)   

我在msdn上查看了

IEnumerable<T> interface and List<T> class. 

下一行来自msdn。

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection,   
IEnumerable

我只是不明白为什么我不能分配

I just don't understand why I can't assign

IEnumerable<ICar> to List<ICar>. 

有人可以向我解释一下。我想念什么。

Can someone please explain this to me. What am I missing.

推荐答案

并非所有 IEnumerable< T> 都是列表< T> 。反之亦然。

Not all IEnumerable<T> are List<T>. The reverse is true.

您可以尝试将其投射到 List< T> ,这是不好的做法,如果确实是这样,可能会失败不是列表,或者您可以通过枚举创建新列表

You can either try to cast to List<T> which is bad practice and could fail if it really is not a list or you can create a new list from the enumeration

new List<T>(yourEnumerable);

或使用Linq

yourEnumerable.ToList();

这篇关于IEnumerable T列出&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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