c# - 将 IEnumerable<T> 添加到派生自 CollectionBase 的类

标签 c# generics collections

假设我有一个 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(object o in collection) 和 foreach(Test in Collection) 期间)。

迭代集合的旧方法和假设集合中的所有项目都是 Test 类型的新方法之间有什么区别吗?我知道添加 IEnumerator 方法会导致程序在发现 Test 以外的任何类型时抛出异常,但想知道我是否忽略了任何内容。

最佳答案

因为你在 2.0(或更高版本),也许只是继承自 Collection<T>

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

然后你得到IList<T> , ICollection<T> , IEnumerable<T>免费,和virtual您可以使用的方法 override在行为上打上你的印记。

关于c# - 将 IEnumerable<T> 添加到派生自 CollectionBase 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1468336/

相关文章:

c# - C#中如何四舍五入到任意数字?

c# - 使用 SignalR 作为独​​立的服务器应用程序,而不是 Asp.Net 应用程序

java - 在java中预定义泛型

collections - Kotlin:在 API 中公开不可变列表

c# - 针对开源内存数据库测试 Oracle SQL 查询

c# - Sonarqube 中的 "This project is empty"错误

generics - F# 方法签名中通用指示符 ' 和符号 ^ 之间有什么区别

c# - 在 C# 中创建虚拟泛型方法

c# - 泛型传递类型成员以对泛型集合进行操作

android - Android google io 2011 java源代码中的MAGIC number