C#: IEnumerable, GetEnumerator, a simple, simple example please!

后端 未结 4 1858
独厮守ぢ
独厮守ぢ 2021-02-05 03:44

Trying to create an uebersimple class that implements get enumerator, but failing madly due to lack of simple / non-functioning examples out there. All I want to do is create a

4条回答
  •  余生分开走
    2021-02-05 04:21

    using System.Collections;
    using System.Collections.Generic;
    
    public class AlbumList : IEnumerable
    {
        private List Albums = new List();
    
        public int Count { get { return Albums.Count; } }
    
        public IEnumerator GetEnumerator()
        {
            return this.Albums.GetEnumerator();
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
    

    or the simplified version:

    public class AlbumList
    {
        private List Albums = new List();
    
        public int Count { get { return Albums.Count; } }
    
        public IEnumerator GetEnumerator()
        {
            return this.Albums.GetEnumerator();
        }
    }
    

    I wouldn't advice leaving out the IEnumerable interface, because you loose integration with .NET such as possibilities to use LINQ, but you can iterate over the collection using a foreach in C#.

    Or this one is even shorter :-)

    public class AlbumList : List
    {
    }
    

    Of course this last one is a mutable list, which perhaps is not exactly what you want.

提交回复
热议问题