问题描述
我想下面的示例给出了当我们实现了IEnumberable接口,我们应该遵循的最佳做法。
的
下面是问题:
- 为什么要提供第二版当前方式的?
- 在当前版本ONE(对象IEnumerator.Current)使用?
- 当版本二(公众人物电流)使用?
- 如何在foreach语句中使用PeopleEnum。 //更新
感谢您
公共类PeopleEnum:IEnumerator的
{
公众人物[] _People;
//枚举定位之前的第一个元素
//直到第一次的MoveNext()调用。
INT位置= -1;
公共PeopleEnum(人[]列表)
{
= _People名单;
}
公共BOOL的MoveNext()
{
位置++;
回报(位置< _people.Length);
}
公共无效复位()
{
位置= -1;
}
//显式接口实现
对象IEnumerator.Current /// **版本ONE **
{
得到
{
返回电流;
}
}
公众人物当前/// **版本二**
{
得到
{
试
{
返回_People [位置]
}
赶上(IndexOutOfRangeException)
{
抛出新的InvalidOperationException异常();
}
}
}
}
我怀疑的原因是,此代码示例从实现的示例类派生的IEnumerator< T>
- 如果示例类 PeopleEnum
实施的IEnumerator< T>
这种方法将需要:的IEnumerator< T>
继承的IEnumerator
所以你必须要实现的两个的实施时,接口的IEnumerator< T>
非泛型的IEnumerator
要求电流$ C $的实施C>返回对象 - 强类型
的IEnumerator< T>
,另一方面需要电流返回类型的实例 T
- 使用显式和直接接口的实现是能够满足需求的唯一途径。
I assume the following sample gives a best practice that we should follow when we implement the IEnumberable interface.
http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.movenext.aspx
Here is the question:
- Why should we provide two version of Current method?
- When the version ONE (object IEnumerator.Current) is used?
- When the version TWO (public Person Current ) is used?
- How to use PeopleEnum in the foreach statement. // updated
Thank you
public class PeopleEnum : IEnumerator
{
public Person[] _people;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public PeopleEnum(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
// explicit interface implementation
object IEnumerator.Current /// **version ONE**
{
get
{
return Current;
}
}
public Person Current /// **version TWO**
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
I suspect the reason is that this code example was derived from an example class implementing IEnumerator<T>
- if the example class PeopleEnum
implemented IEnumerator<T>
this approach would be required: IEnumerator<T>
inherits IEnumerator
so you have to implement both interfaces when implementing IEnumerator<T>
.
The implementation of the non-generic IEnumerator
requires Current
to return object - the strongly typed IEnumerator<T>
on the other hand requires Current to return an instance of type T
- using explicit and direct interface implementation is the only way to fulfill both requirements.
这篇关于C# - 为什么实现IEnumberable接口时实现两个版本的电流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!