好吧,我环顾四周,找不到答案。我有一个返回
的方法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/