为什么 ICollection 索引在实例化时不起作用?
当我们将参数声明为 ICollection 并将对象实例化为 List 时,为什么我们无法检索索引?即
ICollection<ProductDTO> Products = new List<ProductDTO>();
Products.Add(new ProductDTO(1,"Pen"));
Products.Add(new ProductDTO(2,"Notebook"));
然后,这将不起作用:
ProductDTO product = (ProductDTO)Products[0];
我缺少什么?
[是的,我们可以使用 List 作为声明,它可以工作,但我不想声明为列表,例如:
List<ProductDTO> Products = new List<ProductDTO>();
]
When we declare a parameter as ICollection and instantiated the object as List, why we can't retrive the indexes? i.e.
ICollection<ProductDTO> Products = new List<ProductDTO>();
Products.Add(new ProductDTO(1,"Pen"));
Products.Add(new ProductDTO(2,"Notebook"));
Then, this will not work:
ProductDTO product = (ProductDTO)Products[0];
What is the bit I am missing?
[Yes, we can use List as declaration an it can work, but I don't want to declare as list, like:
List<ProductDTO> Products = new List<ProductDTO>();
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用 LINQ,您可以执行以下操作:
Using LINQ, you can do this:
ICollection 接口未声明索引器,因此您不能使用索引通过该类型的引用来获取元素。
您也许可以尝试 IList,它添加了更多功能,同时仍然抽象的。当然,这可能会影响其他设计决策,所以我会仔细考虑这一点。
The ICollection interface doesn't declare an indexer, so you can't use indexing to fetch elements through a reference of that type.
You could perhaps try IList, which adds some more functionality, while still being abstract. Of course, this may impact other design decisions so I would look at this carefully.
ICollection 未定义索引器。
ICollection 非通用
ICollection 通用
ICollection does not define an indexer.
ICollection Non-Generic
ICollection Generic
那么这将起作用:
原因是编译器评估左值,即“=”左侧的变量,以找出它知道哪些方法和属性> 它可以在编译时访问。这称为静态类型,并通过静态地知道成员始终可访问来确保可以在运行时直接访问对象成员。
Then this will work:
The reason is that the compiler evaluates the lvalue, that is the variable on the left side of '=', to find out which methods and properties it knows it can access at compile-time. This is known as static typing, and ensures that an object member can be accessed directly at runtime by statically knowing that the member is always reachable.
基本问题是 ICollection 没有定义索引。对于 List,这是通过 IList 的实现来完成的。
试试这个:
或者,您可以继续使用 ICollection 并在需要通过索引访问元素时转换为数组:
The basic problem is that ICollection doesn't define an index. For the List this is done by the implementation of IList.
Try this:
Alternatly, you can keep using ICollection and convert to an array when you need to access the elements by the index:
使用 Linq,您可以访问 ICollection<> 中的元素。在这样的特定索引处:
Using Linq, you can access an element in an ICollection<> at a specific index like this:
您还可以使用扩展方法将其转换为 ProductDTO 的 (list, array)
然后您可以像这样使用它:
You can also use extension methods to convert it to (list, array) of ProductDTO
Then you can use it like that: