简体   繁体   English

为什么.NET中的这么多命名集合没有实现IEnumerable <T> ?

[英]Why do so many named collections in .NET not implement IEnumerable<T>?

Random example: 随机示例:

ConfigurationElementCollection

.Net has tons of these little WhateverCollection classes that don't implement IEnumerable<T> , which means I can't use Linq to objects with them out of the box. .Net有很多这些没有实现IEnumerable<T>WhateverCollection类,这意味着我不能将Linq用于开箱即用的对象。 Even before Linq, you'd think they would have wanted to make use of generics (which were introduced all the way back in C# 2 I believe) 甚至在Linq之前,你会认为他们会想要使用泛型(我相信它已经在C#2中一直被引入)

It seems I run across these annoying little collection types all the time. 似乎我一直遇到这些讨厌的小集合类型。 Is there some technical reason? 有一些技术原因吗?

The answer is in the question title: "named collections". 答案在问题标题中:“命名集合”。 Which is the way you had to make collections type-safe before generics became available. 在泛型可用之前,您必须使集合类型安全的方式是什么。 There are a lot of them in code that dates back to .NET 1.x, especially Winforms. 代码中有很多可以追溯到.NET 1.x,尤其是Winforms。 There was no reasonable way to rewrite them using generics, that would have broken too much existing code. 没有合理的方法可以使用泛型来重写它们,这会破坏过多的现有代码。

So the named collection type is type safe but the rub is System.Collections.IEnumerator.Current, a property of type Object. 因此,命名集合类型是类型安全的,但rub是System.Collections.IEnumerator.Current,类型为Object的属性。 You can Linqify these collections by using OfType() or Cast(). 您可以使用OfType()或Cast()来Linqify这些集合。

As Adam Houldsworth said in a comment already, you simply need to use the Cast<> method. 正如Adam Houldsworth已经在评论中所说,你只需要使用Cast <>方法。

Example: 例:

var a = new DogCollection();
var allFidos = a.Cast<Dog>().Where(d => d.Name == "Fido"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM