How do I implement IEnumerable?

前端 未结 1 911
抹茶落季
抹茶落季 2020-12-17 03:38

I have a class that contains a static number of objects. This class needs to be frequently \'compared\' to other classes that will be simple List objects.

p         


        
相关标签:
1条回答
  • 2020-12-17 04:01

    You need to create an iterator that returns the Items that reside in the Sheet.

    Using Iterators

    public partial class Sheet
    {
        public Item X{ get; set; }
        public Item Y{ get; set; }
        public Item Z{ get; set; }
    
        public IEnumerable<Item> EnumerateItems()
        {
            yield return X;
            yield return Y;
            yield return Z;
            // ...
        }
    }
    

    If you don't want to have to call the method you can do this.

    public partial class Sheet : IEnumerable<Item>
    {
        public Item X{ get; set; }
        public Item Y{ get; set; }
        public Item Z{ get; set; }
    
        public IEnumerator<Item> GetEnumerator()
        {
            yield return X;
            yield return Y;
            yield return Z;
            // ...
        }
    
        IEnumerator IEnumerator.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    
    0 讨论(0)
提交回复
热议问题