且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何实现 IEnumerable<T>

更新时间:2022-01-24 14:46:14

如果您选择使用泛型集合,例如 List 而不是 ArrayList,您会发现 List 将提供您可以使用的通用和非通用枚举器.

If you choose to use a generic collection, such as List<MyObject> instead of ArrayList, you'll find that the List<MyObject> will provide both generic and non-generic enumerators that you can use.

using System.Collections;

class MyObjects : IEnumerable<MyObject>
{
    List<MyObject> mylist = new List<MyObject>();

    public MyObject this[int index]  
    {  
        get { return mylist[index]; }  
        set { mylist.Insert(index, value); }  
    } 

    public IEnumerator<MyObject> GetEnumerator()
    {
        return mylist.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}