假设我有一个 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/