[英]Why must I define IEnumerator<T>.Current & IEnumerator.Current, and what does that achieve?
When implementing IEnumerable & IEnumerator on a class I was writing during training, I noticed that I was required to specify two implementations for the property "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]; } }
}
I roughly understand that I'm implementing some non-generic version of IEnumerator and a "Current" property for it, however I don't understand the following things: 我粗略地了解到我正在为它实现一些非泛型版本的IEnumerator和一个“当前”属性,但我不明白以下内容:
Thanks in advance! 提前致谢!
There's only one reason you must implement two different interfaces: backwards compatibility. 您必须实现两个不同的接口只有一个原因:向后兼容性。 C# 1.0 did not have generics.
C#1.0没有泛型。
In C# 2.0, we got IEnumerator<T>
which extends the 1.0 IEnumerator
. 在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;
据推测它与显式的IEnumerator.Current有关; however the reasons are opaque to me.
但是原因对我来说是不透明的。
You cannot overload methods or properties by return type only; 您不能仅通过返回类型重载方法或属性; that's why one of them must be an explicit implementation.
这就是为什么其中一个必须是一个明确的实现。
- Why can "object IEnumerator.Current" not be specified as "public"?
为什么“对象IEnumerator.Current”不能被指定为“public”?
Same reason. 同样的道理。 It has to be an explicit implementation.
它必须是一个明确的实现。 An explicit implementation cannot have a visibility modifier as a rule.
显式实现不能将可见性修饰符作为规则。 It cannot possibly have any other visibility.
它不可能有任何其他可见性。
IEnumerator.Current
can only be called through an instance of the IEnumerator
interface. IEnumerator.Current
只能通过IEnumerator
接口的实例调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.