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

C# 2.0 核心新特性速覽:泛型、匿名方法、迭代器與部分類型

     編輯:關於C語言

前言

C# 2.0 引入四大語言擴展,奠定現代 C# 開發基礎。本文快速瀏覽 泛型、匿名方法、迭代器、部分類型 的核心語法與優勢。

1. 泛型

1.1 型別參數化

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

var intStack = new Stack();
intStack.Push(3);
int x = intStack.Pop(); // 無裝箱/拆箱,編譯期型別安全

1.2 多型別參數與約束

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

var dict = new Dictionary();
dict.Add("Key", new Customer());

2. 匿名方法

2.1 內聯委派

button.Click += delegate { listBox.Items.Add(textBox.Text); };

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

2.2 閉包捕獲外部變數

delegate int D();
static D F()
{
    int x = 0;
    return delegate { return ++x; }; // 捕獲 x,生命週期延長
}

3. 迭代器

3.1 yield return 實作 IEnumerable

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

// 自動支援 foreach
foreach (int i in stack) Console.Write(i + " ");

3.2 多種遍歷模式

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

4. 部分類型

4.1 跨檔案定義

// Generated.cs
public partial class Customer { private int Id; public Customer() { } }

// Custom.cs
public partial class Customer { public void SubmitOrder(Order o) { } }

編譯時合併為單一類別,適合程式碼產生器與手寫邏輯分離。

5. 相容性設計

無新增關鍵字,where/yield/partial 僅在特定語境有特殊含義,既有代碼零衝突升級。

結語

C# 2.0 四大特性解決了 1.x 時代的型別安全、委派冗長、集合遍歷困難、大型類別維護等痛點,是進階 C# 開發者必須精通的核心知識。

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