自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

C#編程:使用迭代器

開發(fā) 后端
本文介紹了創(chuàng)建迭代器、調(diào)用迭代器等的方法。創(chuàng)建迭代器最常用的方法是對 IEnumerable 接口實現(xiàn) GetEnumerator 方法。

創(chuàng)建迭代器最常用的方法是對 IEnumerable 接口實現(xiàn) GetEnumerator 方法,例如:

  1. public System.Collections.IEnumerator GetEnumerator()  
  2. {  
  3.     for (int i = 0; i <  max; i++)  
  4.     {  
  5.         yield return i;  
  6.     }  

GetEnumerator 方法的存在使得類型成為可枚舉的類型,并允許使用 foreach 語句。如果上面的方法是 ListClass 的類定義的一部分,則可以對該類使用 foreach,如下所示:

  1. static void Main()  
  2. {  
  3.     ListClass listClass1 = new ListClass();  
  4.  
  5.     foreach (int i in listClass1)  
  6.     {  
  7.         System.Console.WriteLine(i);  
  8.     }  

foreach 語句調(diào)用 ListClass.GetEnumerator() 并使用返回的枚舉數(shù)來循環(huán)訪問值。有關(guān)如何創(chuàng)建返回 IEnumerator 接口的泛型迭代器的示例,請參見 如何:為泛型列表創(chuàng)建迭代器塊(C# 編程指南)。

還可以使用命名的迭代器以支持通過不同的方式循環(huán)訪問同一數(shù)據(jù)集合。例如,您可以提供一個按升序返回元素的迭代器,而提供按降序返回元素的另一個迭代器。迭代器還可以帶有參數(shù),以便允許客戶端控制全部或部分迭代行為。下面的迭代器使用命名的迭代器 SampleIterator 實現(xiàn) IEnumerable 接口:

  1. // Implementing the enumerable pattern  
  2. public System.Collections.IEnumerable SampleIterator(int start, int end)  
  3. {  
  4.     for (int i = start; i < = end; i++)  
  5.     {  
  6.         yield return i;  
  7.     }  

命名的迭代器的調(diào)用方法如下:

  1. ListClass test = new ListClass();  
  2. foreach (int n in test.SampleIterator(1, 10))  
  3. {  
  4.     System.Console.WriteLine(n);  

可以在同一個迭代器中使用多個 yield 語句,如下面的示例所示:

  1. public System.Collections.IEnumerator GetEnumerator()  
  2. {  
  3.     yield return "With an iterator, ";  
  4.     yield return "more than one ";  
  5.     yield return "value can be returned";  
  6.     yield return ".";  

然后可以使用下面的 foreach 語句輸出結(jié)果:

  1. foreach (string element in new TestClass())  
  2. {  
  3.     System.Console.Write(element);  

此示例顯示以下文本:

  1. With an iterator, more than one value can be returned.  

在 foreach 循環(huán)的每次后續(xù)迭代(或?qū)?IEnumerator.MoveNext 的直接調(diào)用)中,下一個迭代器代碼體將從前一個 yield 語句之后開始,并繼續(xù)下一個語句直至到達迭代器體的結(jié)尾或遇到 yield break 語句。

【編輯推薦】

  1. C# winForm自定義鼠標(biāo)樣式的兩種方法
  2. C#自定義消息框的設(shè)置圖解
  3. 掌握C#自定義泛型類:從初始化說起
  4. C#存儲過程的循序漸進
  5. 存儲過程的優(yōu)勢及其調(diào)用方法介紹
責(zé)任編輯:book05 來源: hi.baidu
相關(guān)推薦

2009-08-11 13:59:41

迭代器模式C# Iterator

2009-08-26 16:26:37

C#迭代器模式

2013-03-15 10:37:08

C#

2009-08-26 16:37:07

C#迭代器局部變量

2015-09-16 15:11:58

C#異步編程

2009-08-24 11:02:52

C#接口映射

2009-08-26 10:34:15

C#類型C#變量

2009-08-24 09:55:26

C#接口轉(zhuǎn)換

2025-01-22 08:06:38

C#yield數(shù)據(jù)迭代

2022-10-26 08:25:06

Python編程迭代器

2010-09-28 08:52:00

C#Visual Stud

2012-09-24 15:35:24

C#網(wǎng)絡(luò)協(xié)議UDP

2012-09-24 15:13:50

C#網(wǎng)絡(luò)協(xié)議TCP

2009-08-27 16:30:08

C#編程命名規(guī)范

2011-04-13 17:31:16

C#.NET

2009-08-27 14:12:02

C# interfac

2021-10-12 17:47:22

C# TAP異步

2009-08-14 16:08:34

讀寫B(tài)inaryC#編程實例

2024-03-04 18:49:59

反射C#開發(fā)

2009-08-25 17:13:57

C#串口編程
點贊
收藏

51CTO技術(shù)棧公眾號