【发布时间】:2019-07-09 23:45:03
【问题描述】:
我假设以下示例提供了我们在实现 IEnumerable 接口时应该遵循的最佳实践。
https://docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerator.movenext
问题来了:
- 为什么要提供两个版本的Current方法?
- 何时使用版本 ONE(对象 IEnumerator.Current)?
- 什么时候使用版本二(public Person Current)?
- 如何在 foreach 语句中使用 PeopleEnum。 // 更新了
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();
}
}
}
}
【问题讨论】:
标签: c#