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

C# 2.0 新特性詳解:泛型、匿名方法、迭代器與部分型別

     編輯:關於C語言

前言

C# 2.0 引入四大語言擴展,極大增強了型別安全性、表達能力與開發效率。本文系統整理 泛型、匿名方法、迭代器、部分型別 的核心概念、語法與實戰優勢。

一、泛型

1.1 動機:解決 object 型別缺陷

非泛型集合使用 object 儲存資料,導致三大問題:

  1. 裝箱/拆箱效能損耗:值型別頻繁轉換
  2. 型別安全缺失:編譯期無法攔截錯誤型別,執行期才拋 InvalidCastException
  3. 程式碼冗長:到處充斥強制轉型

1.2 泛型類別定義與使用

public class Stack
{
    T[] items;
    int count;
    public void Push(T item) { ... }
    public T Pop() { ... }
}

// 使用時指定型別參數
Stack intStack = new Stack();
intStack.Push(3);
int x = intStack.Pop(); // 無需轉型,編譯期型別安全

Stack custStack = new Stack();
custStack.Push(new Customer());
// custStack.Push(3); // 編譯錯誤:型別不符

1.3 多型別參數與約束

public class Dictionary where K : IComparable
{
    public void Add(K key, V value) { ... }
    public V this[K key] { ... }
}

// 使用
var dict = new Dictionary();
dict.Add("Peter", new Customer());

where K : IComparable 確保鍵型別可比較,編譯期即檢查,避免執行期轉型失敗。

1.4 泛型方法與型別推斷

void PushMultiple(Stack stack, params T[] values)
{
    foreach (var v in values) stack.Push(v);
}

// 呼叫時可省略 ,編譯器自動推斷
PushMultiple(intStack, 1, 2, 3, 4);

二、匿名方法

2.1 語法與委派轉換

// 傳統寫法
button.Click += new EventHandler(Button_Click);

// 匿名方法
button.Click += delegate { listBox.Items.Add(textBox.Text); };

// 需存取參數時
button.Click += delegate(object sender, EventArgs e) 
{ 
    MessageBox.Show(((Button)sender).Text); 
};

匿名方法可直接內嵌於委派註冊處,並自動捕獲外部區域變數(閉包)。

2.2 外部變數捕獲與生命週期延長

delegate int D();
static D F()
{
    int x = 0;
    return delegate { return ++x; }; // 捕獲 x
}

static void Main()
{
    D d = F();
    Console.WriteLine(d()); // 1
    Console.WriteLine(d()); // 2
    Console.WriteLine(d()); // 3
}

被捕獲的區域變數生命週期延長至委派可被 GC 回收為止。

三、迭代器

3.1 yield return / yield break

實作 IEnumerable<T> 或 IEnumerator<T> 變得極簡單:

public class Stack : IEnumerable
{
    T[] items; int count;
    public IEnumerator GetEnumerator()
    {
        for (int i = count - 1; i >= 0; --i)
            yield return items[i];
    }
}

// 使用 foreach 自動呼叫 GetEnumerator
foreach (int i in stack) Console.Write(i + " ");

3.2 多種遍歷模式

透過屬性回傳不同迭代器:

public IEnumerable TopToBottom { get { return this; } }
public IEnumerable BottomToTop 
{ 
    get 
    { 
        for (int i = 0; i < count; i++) yield return items[i]; 
    } 
}

四、部分型別

4.1 跨檔案定義單一類別

// File1.cs (機器產生)
public partial class Customer
{
    private int id;
    private string name;
    public Customer() { ... }
}

// File2.cs (手寫擴充)
public partial class Customer
{
    public void SubmitOrder(Order o) { ... }
    public bool HasOutstandingOrders() { ... }
}

編譯時自動合併,適用於:

  • 大型類別分模組維護
  • 程式碼產生器與手寫代碼分離,重新產生時不覆蓋自訂邏輯

五、相容性設計

C# 2.0 未新增任何關鍵字,where、yield、partial 僅在特定語境有特殊含義,仍可作為識別碼使用,確保既有代碼零衝突升級。

結語

C# 2.0 的四大特性奠定了現代 C# 開發基石:泛型提供型別安全與效能,匿名方法簡化事件處理,迭代器讓集合遍歷直觀,部分型別支援大型專案協作。掌握它們,是進階 C# 開發者的必修課。

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