T&GT;不能从IEnumerable&LT转换;到ICollection的&LT; T&GT; [英] Cannot convert from an IEnumerable<T> to an ICollection<T>
问题描述
我定义如下:
public ICollection<Item> Items { get; set; }
当我运行此code:
Items = _item.Get("001");
我得到以下信息:
I get the following message:
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差()
Can someone explain what I am doing wrong. I am very confused about the difference between Enumerable, Collections and using the ToList()
补充信息
后来在我的code我有以下几点:
Later in my code I have the following:
for (var index = 0; index < Items.Count(); index++)
我会好起来的定义项目作为一个IEnumerable
Would I be okay to define Items as an IEnumerable?
推荐答案
的ICollection&LT; T&GT;
从继承了IEnumerable&LT; T&GT;
这样的结果分配
IEnumerable<T> Get(string pk)
到的ICollection&LT; T&GT;
有两种方法
// 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&LT; T&GT;
除非你需要用的ICollection&LT添加了额外的功能; T&GT;
接口。
The second options is more flexible, but has a much larger performance impact. Another option is to store the result as an IEnumerable<T>
unless you need the extra functionality added by the ICollection<T>
interface.
您的循环
for (var index = 0; index < Items.Count(); index++)
适用于一个的IEnumerable&LT; T&GT;
,但效率不高;每次调用计数()
需要的完全的枚举的所有元素。无论是使用集合和计数
属性(不带括号),或者将其转换成一个foreach循环:
works on an IEnumerable<T>
but it is inefficient; each call to Count()
requires a complete enumeration of all elements. Either use a collection and the Count
property (without the parenthesis) or convert it into a foreach loop:
foreach(var item in Items)
这篇关于T&GT;不能从IEnumerable&LT转换;到ICollection的&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!