如何实现IEnumerable?
如何实现IEnumerable?
我知道如何实现非泛型的IEnumerable,就像这样:
using System; using System.Collections; namespace ConsoleApplication33 { class Program { static void Main(string[] args) { MyObjects myObjects = new MyObjects(); myObjects[0] = new MyObject() { Foo = "Hello", Bar = 1 }; myObjects[1] = new MyObject() { Foo = "World", Bar = 2 }; foreach (MyObject x in myObjects) { Console.WriteLine(x.Foo); Console.WriteLine(x.Bar); } Console.ReadLine(); } } class MyObject { public string Foo { get; set; } public int Bar { get; set; } } class MyObjects : IEnumerable { ArrayList mylist = new ArrayList(); public MyObject this[int index] { get { return (MyObject)mylist[index]; } set { mylist.Insert(index, value); } } IEnumerator IEnumerable.GetEnumerator() { return mylist.GetEnumerator(); } } }
然而我也注意到IEnumerable有一个泛型版本,IEnumerable
,但我无法弄清如何实现它。
如果我添加using System.Collections.Generic;
到我的使用指令中,然后将:
class MyObjects : IEnumerable
更改为:
class MyObjects : IEnumerable
然后右键单击IEnumerable
并选择实现接口=>实现接口
,Visual Studio会很有用地添加以下代码块:
IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
从GetEnumerator();
方法返回非泛型的IEnumerable对象这次不起作用,那我在这里放什么?当尝试在foreach循环期间枚举我的数组时,CLI现在会直接忽略非泛型实现并进入泛型版本。
admin 更改状态以发布 2023年5月22日
您可能不想要一个明确实现 IEnumerable
的实现(这是您展示的内容)。
通常的模式是在 IEnumerable
的明确实现中使用 IEnumerable
的 GetEnumerator
:
class FooCollection : IEnumerable, IEnumerable { SomeCollection foos; // Explicit for IEnumerable because weakly typed collections are Bad System.Collections.IEnumerator IEnumerable.GetEnumerator() { // uses the strongly typed IEnumerable implementation return this.GetEnumerator(); } // Normal implementation for IEnumerable IEnumerator GetEnumerator() { foreach (Foo foo in this.foos) { yield return foo; //nb: if SomeCollection is not strongly-typed use a cast: // yield return (Foo)foo; // Or better yet, switch to an internal collection which is // strongly-typed. Such as List or T[], your choice. } // or, as pointed out: return this.foos.GetEnumerator(); } }
如果你选择使用通用集合,例如 List
而不是 ArrayList
,你会发现 List
将提供你可以使用的泛型和非泛型枚举器。
using System.Collections; class MyObjects : IEnumerable{ List mylist = new List (); public MyObject this[int index] { get { return mylist[index]; } set { mylist.Insert(index, value); } } public IEnumerator GetEnumerator() { return mylist.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } }