【问题标题】:Why must I define IEnumerator<T>.Current & IEnumerator.Current, and what does that achieve?为什么我必须定义 IEnumerator<T>.Current 和 IEnumerator.Current,这能实现什么?
【发布时间】:2016-05-09 19:49:13
【问题描述】:

在我在训练期间编写的一个类上实现 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;但是原因对我来说是不透明的。
  • 为什么不能将“object IEnumerator.Current”指定为“public”?

提前致谢!

【问题讨论】:

    标签: c#


    【解决方案1】:

    您必须实现两个不同的接口只有一个原因:向后兼容。 C# 1.0 没有泛型。
    在 C# 2.0 中,我们得到了 IEnumerator&lt;T&gt;,它扩展了 1.0 IEnumerator

    • 为什么允许我在这里按返回类型重载?大概它与显式 IEnumerator.Current;但是原因对我来说是不透明的。

    不能仅通过返回类型重载方法或属性;这就是为什么其中之一必须是显式实现。

    • 为什么不能将“object IEnumerator.Current”指定为“public”?

    同样的原因。它必须是一个显式的实现。显式实现通常不能具有可见性修饰符。它不可能有任何其他可见性。 IEnumerator.Current 只能通过IEnumerator 接口的实例调用。

    【讨论】:

    • 这证实了我对这个问题的很多怀疑,谢谢!对属性/方法的显式定义仍然有些困惑,可能需要查看 MSIL 才能真正了解正在发生的事情。
    猜你喜欢
    • 1970-01-01
    • 2014-01-09
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多