首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 2.0 新特性深度解析(二):泛型 IEnumerable/IEnumerator 與手動實作模式

     編輯:關於C語言

非泛型迭代器缺陷

  • 值型別須裝箱/拆箱(`IEnumerator.Current` 回傳 `object`),效能損耗、GC 壓力。
  • 參考型別需向下轉型,程式碼雜訊、執行期風險。
  • C# 1.0 可用「鴨子型別」模式(強型別 `GetEnumerator` 回傳強型別 `IEnumerator`)繞過介面,但非標準。

.NET 2.0 泛型介面


public interface IEnumerable
{
    IEnumerator GetEnumerator();
}
public interface IEnumerator : IDisposable
{
    T Current { get; }
    bool MoveNext();
}
// 無 Reset(),由新實例替代

手動實作範例:城市集合


public class CityCollection : IEnumerable
{
    string[] _cities = {"New York","Paris","London"};
    public IEnumerator GetEnumerator() => new CityEnumerator(this);

    class CityEnumerator : IEnumerator
    {
        CityCollection _collection;
        int _index = -1;
        public CityEnumerator(CityCollection c) { _collection = c; }
        public bool MoveNext() => ++_index < _collection._cities.Length;
        public string Current
        {
            get
            {
                if (_index == -1) throw new InvalidOperationException();
                return _collection._cities[_index];
            }
        }
        public void Dispose() {}
    }
}

編譯器 `foreach` 展開邏輯


// 原始
foreach (string city in cities) Console.WriteLine(city);
// 展開
IEnumerator e = cities.GetEnumerator();
try
{
    while (e.MoveNext())
    {
        string city = e.Current;
        Console.WriteLine(city);
    }
}
finally { e.Dispose(); }

顯式使用 `IEnumerator`

需精確控制迭代流程(如雙指針、合併兩序列)時,可直接操作 `MoveNext`/`Current`,不依賴 `foreach` 語法糖。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved