嗯…
考慮了一下,還是決定把 foreach 特別分出來說明
看這篇之前請先看C# 學習筆記(ver 3)裡面相關的一些規則
1. 用先前的指令建立一個集合。這個集合只能在 C# 程式中。
2. 在實做 IEnumerable 介面之外,用先前的指令建立一個泛用集合。可從其他語言
使用這個集合,例如 Visual Basic 。
3. 在集合類別中使用預先定義的集合。
002_foreach_test.rar
分別對照下面三個範例:
範例1
這個方法簡單來說就是根據 foreach 需要的去實作。
包含 GetEnumerator() 方法
public MyEnumerator GetEnumerator() { return new MyEnumerator(this); } |
自訂的回傳型別
public class MyEnumerator {…} |
回傳型別裡要包含 Current 的屬性
public int Current { get { return (collection.item[nIndex]); } } |
包含回傳值為 bool 的 MoveNext() 方法
public bool MoveNext() { this.nIndex++; return (nIndex < collection.item.GetLength(0)); } |
範例 2-a
主要就是實作相關介面。
1. IEnumerable 介面
namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } } |
自訂集合實做 IEnumerable 介面
class MyCollection2_a : IEnumerable {…} |
實做 GetEnumerator()
IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumrator(); } |
2. IEnumerator 介面
自訂列舉實做 IEnumerator 介面
public class MyEnumerator2_a : IEnumerator {…} |
實作 IEnumerator.Current
object IEnumerator.Current { get { return (this.collection.items[nIndex]); } } |
實作 IEnumerator.MoveNext()
bool IEnumerator.MoveNext() { this.nIndex++; return (nIndex < collection.items.GetLength(0)); } |
實作 IEnumerator.Reset()
void IEnumerator.Reset() { this.nIndex = -1; } |
範例 2-b
與範例 2-a 差不多,但自訂列舉多實作 IDisposable。
IDisposable 介面
namespace System { public interface IDisposable { void Dispose(); } } |
實做 IDisposable.Dispose()
// 書上的寫法 public void Dispose() { Console.WriteLine("處理中…"); this.collection = null; } |
// 改寫後 void IDisposable.Dispose() { Console.WriteLine("處理中…"); this.collection = null; } |
這兩個可同時存在,他自動處理時會call改寫過後的
不知道書上為何這樣寫=_=…有啥原因吧?
範例 3
就是使用現成的集合類別嚕!
Hashtable ziphash = new Hashtable(); |
除了範例 1之外,都要引用 System.collections; 的命名空間喔!
怎麼看還是撿現成的卡簡單,當然有些時候還是要用前兩種吧~