C 列舉器介面IEnumerator的實現

2022-03-09 09:21:56 字數 1551 閱讀 8990

原文(

在c#中,如果乙個類要使用foreach結構來實現迭代,就必須實現ienumerable或ienumerator介面。其中,ienumerator介面定義了實現列舉器模式的方法ienumerator.movenext()和ienumerator.reset()和成員屬性ienumerator.count,而ienumerable介面的唯一方法ienumerable.getenumerator()僅用來返回乙個ienumerator物件,用來間接實現乙個ienumerator介面。

而泛型的ienumerator和ienumerable介面與普通型別的相似,它們是普通型別列舉器介面的泛化形式。但實現ienumerable介面,需要實現兩個getenumerator,分別為ienumerator ienumerable.getenumerator()和ienumeratorgetenumerator()。

1、ienumerator的實現

自己找例子看.....

2、ienumerable的實現

(1)返回乙個ienumerator

自己找例子看.....

(2)使用yield return(yield break)語法

自己找例子看看.....

3、一種混合實現的結構

在乙個類(如classname1)中實現ienumerable介面,而在另乙個類(如classname1enumerator)中實現ienumerator介面,並在classname1中的getenumerator()方法中,返回乙個用classname1例項化的classname1enumerator物件。

4、列舉器具體介紹 

列舉器可用於讀取集合中的資料,但不能用於修改基礎集合。

最初,列舉器被定位於集合中第乙個元素的前面。reset 方法還將列舉器返回到此位置。在此位置,呼叫current 屬性會引發異常。因此,在讀取current 的值之前,必須先通過呼叫movenext 方法將列舉器前移到集合中的第乙個元素。

在呼叫movenext 或reset 之前,current 返回同一物件。movenext 將current 設定到下乙個元素。

如果movenext 越過集合的末尾,則列舉器將放置在集合中最後乙個元素的後面,而且movenext 返回false。當列舉器位於此位置時,對movenext 的後續呼叫也返回false。如果最後一次呼叫movenext 返回了false,則呼叫 current 會引發異常。若要再次將current 設定為集合的第乙個元素,可以呼叫reset,然後再呼叫movenext。

只要該集合保持不變,列舉器也就保持有效。如果對該集合進行了更改(例如新增、修改或刪除元素),則該列舉數變為無效(這一變化是不可恢復的),並且下次呼叫movenext 或reset 將引發invalidoperationexception。如果在movenext 和current 之間修改了集合,則current 會返回已將它設定為的元素,即使該列舉數已失效。

該列舉器不具有獨佔訪問集合的許可權;因此,列舉整個集合本質上不是乙個執行緒安全的過程。即使集合已同步,其他執行緒仍可以修改集合,從而使列舉數引發異常。若要確保列舉過程中的執行緒安全性,可以在整個列舉期間鎖定集合,或者捕獲由其他執行緒進行的更改所導致的異常。

C 列舉 類 多型 介面

列舉 enum day int weekdaystart int day.mon 類 物件是類的例項。構成類的方法和變數成為類的成員 當你定義乙個類時,你定義了乙個資料型別的藍圖。這實際上並沒有定義任何的資料,但它定義了類的名稱意味著什麼,也就是說,類的物件由什麼組成及在這個物件上可執行什麼操作。類...

C 迭代器,列舉器

測試 using system using system.collections.generic using system.linq using system.text using system.collections namespace 07迭代器 private int move 0 const...

C 列舉器和迭代器

using system using system.collections namespace study public class people ienumerable 宣告可列舉類 ienumerator ienumerable.getenumerator 實現ienumerable的geten...