我定义了以下内容:
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?)
有人能解释一下我做错了什么吗?我对枚举、集合和使用ToList()之间的区别感到非常困惑。
添加了信息
在我后面的代码中,我有以下内容:
for (var index = 0; index < Items.Count(); index++)
我可以将项目定义为IEnumerable吗?
发布于 2012-01-01 19:04:36
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)
发布于 2012-01-01 18:54:20
不能直接从IEnumerable<T>
转换为ICollection<T>
。您可以使用IEnumerable<T>
的ToList
方法将其转换为ICollection<T>
someICollection = SomeIEnumerable.ToList();
发布于 2012-01-01 18:52:18
等待有关该问题的更多信息:
请提供更多Get的商品类型和签名信息
你可以尝试的两件事是:
请注意,第二个将导致阵列拷贝的性能受到影响。如果Get的签名(返回类型)不是ICollection,则第一个不起作用;如果不是IEnumerable,则第二个不起作用。
在您对问题和评论进行澄清之后,我个人将向ICollection声明_item.Get("001")的返回类型。这意味着您不必进行任何转换或转换(通过ToList / ToArray),这将涉及不必要的创建/复制操作。
// Leave this the same
public ICollection<Item> Items { get; set; }
// Change function signature here:
// As you mention Item uses the same underlying type, just return an ICollection<T>
public ICollection<Item> Get(string value);
// Ideally here you want to call .Count on the collectoin, not .Count() on
// IEnumerable, as this will result in a new Enumerator being created
// per loop iteration
for (var index = 0; index < Items.Count(); index++)
诚挚的问候,
https://stackoverflow.com/questions/8692742
复制相似问题