C# - How to implement IEnumerator on a class

后端 未结 3 504
南旧
南旧 2020-12-18 22:29

How to implement IEnumerator on this class so that I can use it in foreach loop.

public class Items
    {
        private Dictionary

        
3条回答
  •  醉话见心
    2020-12-18 22:48

    Just an example to implement typesafe IEnumerable and not IEnumerator which you will be able to use in foreach loop.

       public class Items : IEnumerable
        {
            private Dictionary _items = new Dictionary();
    
    
            public void Add(string element, Configuration config) {
                _items[element] = config;
            }
    
            public Configuration this[string element]
            {
                get
                {
    
                    if (_items.ContainsKey(element))
                    {
                        return _items[element];
                    }
                    else
                    {
                        return null;
                    }
                }
    
                set
                {
                    _items[element] = value;
                }
            }
    
            public IEnumerator GetEnumerator()
            {
                return _items.Values.GetEnumerator();
            }
    
            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return _items.Values.GetEnumerator();
            }
        }
    

    Regards.

提交回复
热议问题