c# – 为什么我必须定义IEnumerator.Current和IEnumerator.Current,它实现了什么?

实现IEnumerable&我在训练期间写的一个类的IEnumerator,我注意到我需要为属性“Current”指定两个实现.
public class PeopleEnumerator : IEnumerator<Person>
{
    People people; // my collection I'm enumerating (just a wrapped array).
    int index; // my index to keep track of where in the collection I am.

    ...

    //implementation for Person
    public Person Current { get { return people[index]; } }

    //implementation for object
    object Enumerator.Current { get { return people[index]; } }
}

我粗略地了解到我正在为它实现一些非泛型版本的IEnumerator和一个“当前”属性,但我不明白以下内容

>为什么我允许在这里通过返回类型重载?据推测它与显式的IEnumerator.Current有关;但是原因对我来说是不透明的.
>为什么“对象IEnumerator.Current”不能被指定为“公共”?

提前致谢!

解决方法

您必须实现两个不同的接口只有一个原因:向后兼容性. C#1.0没有泛型.
在C#2.0中,我们得到了IEnumerator< T>它扩展了1.0 IEnumerator.
  • Why am I allowed to overload by return type here? Presumably it has something to do with the explicit IEnumerator.Current; however the reasons are opaque to me.

您不能仅通过返回类型重载方法属性;这就是为什么其中一个必须是一个明确的实现.

  • Why can “object IEnumerator.Current” not be specified as “public”?

同样的道理.它必须是一个明确的实现.显式实现不能将可见性修饰符作为规则.它不可能有任何其他可见性. IEnumerator.Current只能通过IEnumerator接口的实例调用.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...