c# - IEnumerable<T> 到 List<T>

标签 c# c#-4.0

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

的方法
IEnumerable<ICar> 

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

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

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

IEnumerable<ICar> to List<ICar>. 

谁能给我解释一下。我错过了什么。

最佳答案

不是所有IEnumerable<T>List<T> .反之亦然。

您可以尝试转换为 List<T>这是一种不好的做法,如果它确实不是列表,则可能会失败,或者您可以从枚举中创建一个新列表

new List<T>(yourEnumerable);

或使用 Linq

yourEnumerable.ToList();

关于c# - IEnumerable<T> 到 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10406410/

相关文章:

c# - Asp.Net 4.0 中的路由

c# - 在网格中显示货币符号

c# - Selenium Webdriver C# 如何测试一个元素不存在?

c# - 从表单中读取字符串作为逐字字符串,\\显示而不是\

c#-4.0 - 如何在 Windows Phone 8 中使列表框不可滚动

c# - 如何用C#绘制流畅的图像?

c# - C# 中的 Nodejs 等效于流式 IO,无需缓冲来自 requestContext 的内容

asp.net-mvc - 如何配置 Nhibernate 不在当前 session 中保存对象

c# - C#中switch语句的多个变量

c# - 为什么我得到 'One or more types required to compile a dynamic expression cannot be found.' ?