为什么在声明接口方法时不 "IEnumerator IEnumerator.GetEnumerator()" ? IEnumerable接口

Why not "IEnumerator IEnumerator.GetEnumerator()" while declaring the interface method ? IEnumerable interface

我有 3 个关于 IEnumerable<T>IEnumerator<T> 界面的问题:

  1. 为什么不IEnumerator IEnumerator.GetEnumerator(),因为它是接口方法?

  2. 为什么不能public?

  3. 为什么返回值 Current 应该是一个对象,即使我知道具体类型?

代码:(题目已标出)

 public class myIEnumCollection : IEnumerable<int> 
        {
            public IEnumerator GetEnumerator() // 1)
            {
                return new myIEnumerator();           
            }

            IEnumerator<int> IEnumerable<int>.GetEnumerator(){ // 2)  
                throw new NotImplementedException();
            }
        }

        public class myIEnumerator: IEnumerator<int> {

            public int Current{get; private set; } = 0;
            object IEnumerator.Current => Current; // 3)

            public bool MoveNext(){ 
                Current++;    
                return true; 
            }
            public void Reset() {
                Current = 0;
            } 

            public void Dispose(){

            }
        }

谢谢!

  1. 我认为你的实现被颠倒了。如果您遵循 IEnumerable<T>'s page 上的示例代码,您将像这样声明它:
public IEnumerator<int> GetEnumerator()
{
    return new myIEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
    throw new NotImplementedException();
}
  1. IEnumerable<T> implements the non-generic interface IEnumerable and both define a method GetEnumerable() with different return types. Because of this, only one of these methods can be directly accessed (see this question for more information: C# Interfaces. Implicit implementation versus Explicit implementation)
  2. 与2相关,IEnumerator<T> implements the non-generic interface IEnumerator定义为对象