繁体   English   中英

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

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

假设我有一个类TestCollection,用于保存Test类型的对象并定义为

public class TestCollection : CollectionBase

这允许我以集合方式遍历集合

foreach(object o in collection)
...

要么

foreach(Test t in collection)

但是不允许我使用新的Linq查询。

如果我将类的定义更改为

public class TestCollection : CollectionBase, IEnumerable<Test>

并添加一个方法

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

然后linq查询可用。

但是,这个新方法不仅仅调用linq查询,而且还在遗留代码中调用(即在foreach(集合中的对象o)和foreach(集合中的Test)期间)。

迭代通过集合的旧方法和假设集合中的所有项目都是Test类型的新方法之间有什么区别吗? 我知道添加IEnumerator方法会导致程序抛出异常,如果它找到除Test之外的任何类型,但想知道我是否忽略了任何东西。

既然你是2.0(或更高),也许只是从Collection<T>继承?

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

然后你可以免费获得IList<T>ICollection<T>IEnumerable<T> ,以及你可以override virtual方法,以便对行为进行标记。

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

从迭代器编译的IEnumerator<T>不实现Reset方法。 编辑 :我的意思是它将抛出一个NotImplementedException

这没有什么实际的错误,但如果你想要Reset方法,你将不得不编写自己的迭代器类,这并不难。

暂无
暂无

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

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