[英]How Can I Use IEnumerator.Reset()?
調用IEnumerator.Reset
的正確方法到底是什么?
該文件說:
提供了
Reset
方法以實現COM互操作性。 它不一定需要實施; 相反,實現者可以簡單地拋出NotSupportedException
。
好吧,這是否意味着我不應該打電話呢?
使用異常進行流控制非常誘人:
using (enumerator = GetSomeExpensiveEnumerator())
{
while (enumerator.MoveNext()) { ... }
try { enumerator.Reset(); } //Try an inexpensive method
catch (NotSupportedException)
{ enumerator = GetSomeExpensiveEnumerator(); } //Fine, get another one
while (enumerator.MoveNext()) { ... }
}
那是我們應該如何使用它? 還是我們根本不打算在托管代碼中使用它?
從不 ; 最終這是一個錯誤。 多次重復序列的正確方法是再次調用.GetEnumerator()
-即再次使用foreach
。 如果您的數據不可重復(或重復成本很高),請通過.ToList()
或類似方法對其進行緩沖。
在語言規范中,正式要求迭代器塊為此方法引發異常。 因此,您不能依靠它來工作 。 曾經
我建議不要使用它。 許多現代的IEnumerable
實現都會拋出異常。
獲取枚舉數幾乎從來都不是“昂貴的”。 它(全部)枚舉了所有可能很昂貴的東西。
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;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Person Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.