c# - 无法从 IEnumerable<T> 转换为 ICollection<T>

标签 c# .net

我定义了以下内容:

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/

相关文章:

c# - 如何区分 T 和 IList<T>

c# - EF Core 1.1 到 WebApi Core - 添加迁移失败

javascript - Ajax 安全性和代码隐藏功能

c# - 如何以编程方式创建 ASP.NET MVC 项目?

c# - 使用参数执行查询

c# - 为什么我的调试器似乎卡在 await 语句中?

c# - 将设置写入注册表,由 x64 和 x86 应用程序共享(绕过注册表重定向)

c# - EventSource 未写入 SQL 数据库

c# - 将 Redis 与 C# : value is not an integer or out of range, sPort : 51410, LastCommand 一起使用时出错:

c# - 锁定属性