How do I implement IEnumerable in my Dictionary wrapper class that implements IEnumerable?

后端 未结 7 2031
走了就别回头了
走了就别回头了 2021-02-08 12:56

I\'m trying to create a wrapper for a Dictionary.

Dictionary implements IEnumerable

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 13:44

    When implementing IEnumerable, you must also explicitly implement IEnumerable.GetEnumerator(). The method for the generic interface is not valid in and of itself as an implementation for the non-generic method contract. You can have one call the other, or since you have a child object whose enumerator you are using, just copy/paste;

    using System.Collections;
    using System.Collections.Generic;
    
    public class FooCollection : IEnumerable
    {
        private Dictionary fooDictionary = new Dictionary();
    
        public IEnumerator GetEnumerator()
        {
            return fooDictionary.Values.GetEnumerator();
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            //forces use of the non-generic implementation on the Values collection
            return ((IEnumerable)fooDictionary.Values).GetEnumerator();
        }
    
        // Other wrapper methods omitted
    
    }
    

提交回复
热议问题