【问题标题】:Why not "IEnumerator IEnumerator.GetEnumerator()" while declaring the interface method ? IEnumerable interface为什么在声明接口方法时不使用“IEnumerator IEnumerator.GetEnumerator()”? IEnumerable 接口
【发布时间】:2021-04-16 20:50:03
【问题描述】:

我有3个关于IEnumerable<T>IEnumerator<T>接口的问题:

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

  2. 为什么不能公开?

  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(){

            }
        }

谢谢!

【问题讨论】:

  • "为什么它不会崩溃?" - 如果您最终调用它,它将(带有NotImplementedException)。你根本没有展示你是如何使用它的。总的来说,我发现您的问题很难理解 - 部分原因是您在一篇文章中提出了四个问题。如果您在每个帖子中问 一个 问题,Stack Overflow 的效果会更好。
  • 我没有使用它(空的主要方法)。目的是让它可运行
  • 我希望现在更好。

标签: c# interface ienumerable


【解决方案1】:
  1. 我认为您的实现方式颠倒了。如果您遵循IEnumerable&lt;T&gt;'s page 上的示例代码,您可以这样声明:
public IEnumerator<int> GetEnumerator()
{
    return new myIEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
    throw new NotImplementedException();
}
  1. IEnumerable&lt;T&gt; implements the non-generic interface IEnumerable 并且都定义了具有不同返回类型的方法 GetEnumerable()。因此,只能直接访问其中一种方法(有关更多信息,请参阅此问题:C# Interfaces. Implicit implementation versus Explicit implementation
  2. 与 2 相关,IEnumerator&lt;T&gt; implements the non-generic interface IEnumerator 将其定义为对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 2013-08-24
    • 1970-01-01
    相关资源
    最近更新 更多