且构网

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

我如何实现IEnumerable< T>

更新时间:2022-01-24 14:47:02

如果您选择使用泛型集合,如名单,其中,为MyObject> 而不是的ArrayList ,你会发现名单,其中,为MyObject> 将提供通用和非通用枚举,您可以使用

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.

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();
    }

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