C#foreach使用實例淺析
作者:anjou
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 類
- /// <summary>
- /// MySplit 類
- /// </summary>
- public class MySplit : IEnumerable
- {
- private string[] elements;
- public MySplit(string source, char[] delimiters)
- {
- elements = source.Split(delimiters);
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return new MyEnumerator(this);
- }
- #region 在嵌套類中實現(xiàn) IEnumerator 接口
- /// <summary>
- /// 在嵌套類中實現(xiàn) IEnumerator 接口,以便以后方便創(chuàng)建多個枚舉
- /// </summary>
- public class MyEnumerator : IEnumerator
- {
- private int position = -1;
- private MySplit t;
- public MyEnumerator(MySplit t)
- {
- this.t = t;
- }
- public bool MoveNext()
- {
- if (position < t.elements.Length - 1)
- {
- position++;
- return true;
- }
- else
- {
- return false;
- }
- }
- public void Reset()
- {
- position = -1;
- }
- object IEnumerator.Current
- {
- get
- {
- try
- {
- return t.elements[position];
- }
- catch (IndexOutOfRangeException)
- {
- throw new InvalidOperationException();
- }
- }
- }
- }
- #endregion
- }
C# foreach使用2. 使用過程(注意規(guī)范)
- MySplit mySplit = new MySplit("大豆男生: I Love You!", new char[] { ' ', '-' });
- foreach (string item in mySplit)
- {
- Console.WriteLine(item);
- }
C# foreach使用3. 程序輸出結(jié)果
- 大豆男生:
- I
- Love
- You!
C# foreach使用的情況就向你介紹到這里,希望對你了解和學(xué)習(xí)以及C# foreach使用有所幫助。
【編輯推薦】
責(zé)任編輯:仲衡
來源:
博客園