C# - How to implement IEnumerator on a class

后端 未结 3 503
南旧
南旧 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:54

    You should be able to implement IEnumerator like this:

    public class Items : IEnumerator>  
    {        
        private Dictionary _items = new Dictionary();        
        public Configuration this[string element]       
        {            
            get
            {
                if (_items.ContainsKey(element))
                {
                    return _items[element];
                }
                else
                {
                    return null;
                }
            }
            set
            {
                 _items[element] = value;
            }
        }
    
        int current;
        public object Current
        {
            get { return _items.ElementAt(current); }
        }
    
        public bool MoveNext()
        {
            if (_items.Count == 0 || _items.Count <= current)
            {
                return false;
            }
            return true;
        }
    
        public void Reset()
        {
            current = 0;
        }
    
        public IEnumerator GetEnumerator()
        {
            return _items.GetEnumerator();
        }
    
        KeyValuePair IEnumerator>.Current
        {
            get { return _items.ElementAt(current); }
        }
    
        public void Dispose()
        {
            //Dispose here
        }
    }
    

    But as already noted you could also just implement IEnumerable.

提交回复
热议问题