我定义了以下内容:
public ICollection<Item> Items { get; set; }
当我运行这段代码时:
Items = _item.Get("001");
我收到以下消息:
Error 3
Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<Storage.Models.Item>' to
'System.Collections.Generic.ICollection<Storage.Models.Item>'.
An explicit conversion exists (are you missing a cast?)
谁能解释一下我做错了什么。我很困惑 Enumerable、Collections 和使用 ToList() 之间的区别
添加信息
稍后在我的代码中我有以下内容:
for (var index = 0; index < Items.Count(); index++)
我可以将 Items 定义为 IEnumerable 吗?
最佳答案
ICollection<T>
继承自 IEnumerable<T>
所以分配
IEnumerable<T> Get(string pk)
到ICollection<T>
有两种方法。
// 1. You know that the referenced object implements `ICollection<T>`,
// so you can use a cast
ICollection<T> c = (ICollection<T>)Get("pk");
// 2. The returned object can be any `IEnumerable<T>`, so you need to
// enumerate it and put it into something implementing `ICollection<T>`.
// The easiest is to use `ToList()`:
ICollection<T> c = Get("pk").ToList();
第二个选项更灵活,但对性能的影响要大得多。另一种选择是将结果存储为 IEnumerable<T>
。除非你需要 ICollection<T>
添加的额外功能界面。
附加性能评论
你的循环
for (var index = 0; index < Items.Count(); index++)
在 IEnumerable<T>
上工作但效率低下;每次调用Count()
需要所有元素的完整枚举。使用集合和 Count
属性(不带括号)或将其转换为 foreach 循环:
foreach(var item in Items)
关于c# - 无法从 IEnumerable<T> 转换为 ICollection<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8692742/