简体   繁体   English

添加IEnumerable <T> 从CollectionBase派生的类

[英]Adding IEnumerable<T> to class derived from CollectionBase

Suppose I have a class TestCollection which is used to hold objects of type Test and is defined as 假设我有一个类TestCollection,用于保存Test类型的对象并定义为

public class TestCollection : CollectionBase

This allows me to iterate through the collection either as 这允许我以集合方式遍历集合

foreach(object o in collection)
...

or 要么

foreach(Test t in collection)

but does not allow me to use new Linq queries. 但是不允许我使用新的Linq查询。

If I change the definition of the class to 如果我将类的定义更改为

public class TestCollection : CollectionBase, IEnumerable<Test>

and add a method 并添加一个方法

public new IEnumerator<Test> GetEnumerator()
{
    foreach (Test o in this.List)
        yield return o ;
}

then linq queries are available. 然后linq查询可用。

However this new method is not just called for linq queries, but is also called in the legacy code (ie during the foreach(object o in collection) and foreach(Test in Collection). 但是,这个新方法不仅仅调用linq查询,而且还在遗留代码中调用(即在foreach(集合中的对象o)和foreach(集合中的Test)期间)。

Is there any difference between the old way of iterating through the collection and this new way assuming all the items in the collection are of type Test? 迭代通过集合的旧方法和假设集合中的所有项目都是Test类型的新方法之间有什么区别吗? I am aware that adding the IEnumerator method will cause the program to throw an exception if it finds any types other than Test, but want to know if I have overlooked anything. 我知道添加IEnumerator方法会导致程序抛出异常,如果它找到除Test之外的任何类型,但想知道我是否忽略了任何东西。

Since you are in 2.0 (or above), perhaps just inherit from Collection<T> ? 既然你是2.0(或更高),也许只是从Collection<T>继承?

public class TestCollection : Collection<Test> {
    // your extra code here
}

Then you get IList<T> , ICollection<T> , IEnumerable<T> for free, and virtual methods that you can override to put your stamp on the behaviour. 然后你可以免费获得IList<T>ICollection<T>IEnumerable<T> ,以及你可以override virtual方法,以便对行为进行标记。

不,您将看到相同的结果,只会遇到一个额外的间接级别(因为新的GetEnumerator方法只调用现有的GetEnumerator方法并流式传输其输出)。

The IEnumerator<T> compiled from an iterator doesn't implement the Reset method. 从迭代器编译的IEnumerator<T>不实现Reset方法。 EDIT : I mean that it will throw a NotImplementedException . 编辑 :我的意思是它将抛出一个NotImplementedException

There's nothing actually wrong with that, but if you want the Reset method, you'll have to write your own iterator class, which isn't hard. 这没有什么实际的错误,但如果你想要Reset方法,你将不得不编写自己的迭代器类,这并不难。

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

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