[英]Is there a built-in way to convert IEnumerator to IEnumerable
[英]Does foreach use IEnumerator/IEnumerable for built-in types?
foreach循環是否僅使用接口IEnumerator
和IEnumerable
來迭代自定義類型(類)的對象,還是迭代內置類型(在幕后)?
Foreach並不依賴於IEnumerable
。 但是,如果一個類型實現它,那么foreach循環將能夠枚舉它(基於模式的匹配)。
在幕后它只需要一個GetEnumerator()
方法,枚舉器必須包含Current
和MoveNext()
。
來自MSDN:
集合類型:
- 必須是以下類型之一: interface , class或struct 。
- 必須包含一個名為GetEnumerator的實例方法,該方法返回一個類型,例如
Enumerator
(如下所述)。類型
Enumerator
(類或結構)必須包含:
- 一個名為Current的屬性,它返回
ItemType
或可以轉換為它的類型。 屬性訪問器返回集合的當前元素。- 一個名為MoveNext的 bool方法,它遞增項目計數器,如果集合中有更多項目,則返回true 。
更新 :請參閱更新的MSDN頁面 - 如何:使用foreach訪問集合類(C#編程指南) 。
定義枚舉器,沒有IEnumerable聲明。
public class WorkInfoEnumerator
{
List<WorkItem > wilist= null;
int currentIndex = -1;
public MyClassEnumerator(List<WorkItem > list)
{
wilist= list;
}
public WorkItem Current
{
get
{
return wilist[currentIndex];
}
}
public bool MoveNext()
{
++currentIndex;
if (currentIndex < wilist.Count)
return true;
return false;
}
}
public class WorkInfo
{
List<WorkItem > mydata = new List<WorkItem >();
public WorkInfoEnumerator GetEnumerator()
{
return new WorkInfoEnumerator(mydata);
}
}
代碼中的某處可以使用:
WorkInfo wi = new WorkInfo();
foreach(WorkItem witem in wi)
{
}
foreach對本機和自定義類型使用IEnumerable。 例如,如果您查看System.Array(它是所有數組類型的基礎),它將實現IEnumerable。
for-each是語言構造,並沒有真正區分自定義/內置類型。
對於每個不依賴於IEnumerable
,它使用基於模式的匹配。 見http://blogs.msdn.com/b/ericlippert/archive/2011/06/30/following-the-pattern.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.