我假设以下示例给出了我们在实现IEnumberable接口时应遵循的最佳实践。C# - 为什么在实现IEnumberable接口时实现两个Current版本?
http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.movenext.aspx
这里有一个问题:
- 我们为什么要提供两个版本当前方法吗?
- 当版本ONE(对象IEnumerator.Current)被使用?
- 当使用TWO(公共人物当前)版本时?
- 如何在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();
}
}
}
}
我刚刚发现你实际上给出了我需要的答案。 - 谢谢 – q0987 2011-05-07 02:27:56