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

后端 未结 4 1864
独厮守ぢ
独厮守ぢ 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:18

    Based on your comment that you want to have a wrapper around a data structure (the list), and an enumerator function to return an Album, I think you're talking about indexer properties, right? This is how you do it:

    public class Album
    {
        public readonly string Artist;
        public readonly string Title;
        public Album(string artist, string title)
        {
             Artist = artist;
             Title = title;
        } 
    }
    
    public class AlbumList
    {
        private List Albums = new List();
        public int Count
        {
            get { return Albums.Count; }
        }
    
        public Album this[int index]
        {
            get
            {
                return Albums[index];
            }
        }
    
        public Album this[string albumName]
        {
            get
            {
                return Albums.FirstOrDefault(c => c.Title == albumName);
            }
        }
    
        public void Add(Album album)
        {
            Albums.Add(album);
        }
    
        public void Remove(Album album)
        {
            Albums.Remove(album);
        }
    }
    

    A small console program:

            AlbumList albums = new AlbumList();
            albums.Add(new Album { Artist = "artist1", Title = "title1" });
            albums.Add(new Album { Artist = "artist2", Title = "title2" });
    
            for (int i = 0; i < albums.Count; i++)
            {
                Console.WriteLine(albums[i].Artist);
                Console.WriteLine(albums[i].Title);
            }
    
            Console.WriteLine("title for artist1");
            Console.WriteLine(albums["artist1"].Title);
    

提交回复
热议问题