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

C#foreach使用實例淺析

開發(fā) 后端
C# foreach使用過程就是一個遍歷的過程,那么在C# foreach使用的過程中我們要注意實現(xiàn)IEnumerable 和IEnumerator兩個接口,C# foreach應(yīng)用規(guī)范。

C# foreach使用實例向你全面展示了C# foreach的使用規(guī)范,以及在C# foreach中特別要注意的關(guān)鍵是實現(xiàn)IEnumerable 和IEnumerator 這兩個接口:那么學(xué)習(xí)C# foreach這一C#新加入的語句,我們還是要多多練習(xí)和體會。

C# foreach使用1. MySplit 類

  1. /// <summary>  
  2.  /// MySplit 類  
  3.  /// </summary>  
  4.  public class MySplit : IEnumerable  
  5.  {  
  6. private string[] elements;  
  7.  
  8. public MySplit(string source, char[] delimiters)  
  9. {  
  10. elements = source.Split(delimiters);  
  11. }  
  12.  
  13. IEnumerator IEnumerable.GetEnumerator()  
  14. {  
  15. return new MyEnumerator(this);  
  16. }  
  17.  
  18. #region 在嵌套類中實現(xiàn) IEnumerator 接口  
  19. /// <summary>  
  20. /// 在嵌套類中實現(xiàn) IEnumerator 接口,以便以后方便創(chuàng)建多個枚舉  
  21. /// </summary>  
  22. public class MyEnumerator : IEnumerator  
  23. {  
  24. private int position = -1;  
  25. private MySplit t;  
  26.  
  27. public MyEnumerator(MySplit t)  
  28. {  
  29.  this.t = t;  
  30. }  
  31.  
  32. public bool MoveNext()  
  33. {  
  34.  if (position < t.elements.Length - 1)  
  35.  {  
  36. position++;  
  37. return true;  
  38.  }  
  39.  else 
  40.  {  
  41. return false;  
  42.  }  
  43. }  
  44.  
  45. public void Reset()  
  46. {  
  47.  position = -1;  
  48. }  
  49.  
  50. object IEnumerator.Current  
  51. {  
  52.  get 
  53.  {  
  54. try 
  55. {  
  56. return t.elements[position];  
  57. }  
  58. catch (IndexOutOfRangeException)  
  59. {  
  60. throw new InvalidOperationException();  
  61. }  
  62.  }  
  63. }  
  64. }  
  65. #endregion  
  66.  }  

C# foreach使用2. 使用過程(注意規(guī)范)

  1. MySplit mySplit = new MySplit("大豆男生: I Love You!"new char[] { ' ''-' });  
  2.  foreach (string item in mySplit)  
  3.  {  
  4. Console.WriteLine(item);  
  5.  } 

C# foreach使用3. 程序輸出結(jié)果

  1. 大豆男生:  
  2. I  
  3. Love  
  4. You! 

C# foreach使用的情況就向你介紹到這里,希望對你了解和學(xué)習(xí)以及C# foreach使用有所幫助。

【編輯推薦】

  1. .NET Framework詳解之內(nèi)存機制
  2. 脫離.net framework的C#程序
  3. 詳解基于C#的.NET Framework
  4. C#foreach語句使用體會
  5. C# foreach語句概念及使用淺析
責(zé)任編輯:仲衡 來源: 博客園
相關(guān)推薦

2009-08-27 10:20:03

C# foreach語

2009-08-27 09:49:10

C# foreach語

2009-08-27 11:12:04

C# foreach

2009-08-27 11:27:58

foreach語句C# foreach語

2009-07-31 18:39:31

C#中foreach引

2009-08-13 14:56:46

C#的結(jié)構(gòu)體使用

2009-08-26 13:36:33

C#打印控件

2009-08-27 13:30:11

C# interfac

2009-08-18 13:49:21

C# 操作Excel

2009-08-27 17:59:56

C#接口定義

2009-08-17 17:49:20

C# 枚舉

2009-09-09 13:57:28

C# XML解析

2009-08-31 18:38:59

C#寫文件

2009-09-01 13:13:28

C#打開Word文檔

2009-08-19 11:34:06

C#操作Word

2009-09-03 14:55:34

C#計算時間間隔

2009-08-19 11:13:49

C#操作Word

2009-08-12 15:26:38

C#讀取XML文檔

2009-08-28 17:34:14

讀取word文檔

2009-08-18 16:04:12

C# 操作Excel
點贊
收藏

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