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

C# 2.0 新特性深度解析:匿名方法、迭代器、部分類型與靜態類別

     編輯:關於C#

C# 2.0 引入多項提升開發效率的語言特性。本文系統整理匿名方法、迭代器、部分類型、靜態類別、全域命名空間限定符、編譯器警告控制等核心功能,附 IL 層級實作原理分析。

迭代器:yield return 的威力

傳統實作 IEnumerable 需手寫巢狀列舉器類別。C# 2.0 編譯器自動生成狀態機:

基本用法

public class CityCollection : IEnumerable<string> {
    string[] cities = { "New York", "Paris", "London" };
    public IEnumerator<string> GetEnumerator() {
        for (int i = 0; i < cities.Length; i++)
            yield return cities[i];
    }
}

多重迭代器

public IEnumerable<string> Reverse {
    get {
        for (int i = cities.Length - 1; i >= 0; i--)
            yield return cities[i];
    }
}

// 使用
foreach (string city in collection.Reverse) { ... }

遞迴迭代:二元樹中序遍歷

public class BinaryTree<T> : IEnumerable<T> where T : IComparable<T> {
    Node<T> root;
    
    public IEnumerable<T> InOrder => ScanInOrder(root);
    
    IEnumerable<T> ScanInOrder(Node<T> node) {
        if (node.Left != null)
            foreach (T item in ScanInOrder(node.Left)) yield return item;
        yield return node.Item;
        if (node.Right != null)
            foreach (T item in ScanInOrder(node.Right)) yield return item;
    }
}

效能提醒:遞迴迭代每層呼叫產生新迭代器物件,深度樹可能產生大量 Gen0 物件。高效能場景建議改用堆疊手動實作。

部分類型:跨檔案定義類別

// File1.cs
public partial class MyClass {
    public void Method1() { }
}

// File2.cs
public partial class MyClass : IMyInterface {
    public void Method2() { }
    public int Number;
}

規則:

  • 所有部分須相同存取修飾詞與基底類別(非累積)
  • 介面實作可累積
  • 不可跨組件
  • 編譯時合併為單一型別,IL 無部分痕跡

匿名方法:內嵌委托實作

基本語法

delegate void SomeDelegate();
SomeDelegate d = delegate { MessageBox.Show("Hello"); };
d();

參數與外部變數捕獲

delegate void D(string s);
D d = delegate(string s) { Console.WriteLine(s); };
d("Hello");

// 捕獲區域變數
string msg = "Hello";
D d2 = delegate(string name) { Console.WriteLine(msg + " " + name); };
d2("World");

編譯器實作原理

  • 無捕獲變數:生成私有方法 __AnonymousMethod$XXX
  • 有捕獲變數:生成巢狀類別 __LocalsDisplayClass$XXX 包含捕獲變數與 <this> 參考

實用範例:執行緒安全的 Label

public class SafeLabel : Label {
    delegate void SetTextDel(string text);
    delegate string GetTextDel();
    
    public override string Text {
        set {
            if (InvokeRequired) 
                Invoke(new SetTextDel(delegate(string t) { base.Text = t; }), value);
            else base.Text = value;
        }
        get {
            if (InvokeRequired)
                return (string)Invoke(new GetTextDel(delegate { return base.Text; }));
            return base.Text;
        }
    }
}

委托推論:簡化語法

// C# 1.1
SomeDelegate d = new SomeDelegate(MethodName);

// C# 2.0
SomeDelegate d = MethodName;

// 異步呼叫雙重推論
delegate int Calc(int x, y);
Calc c = (a, b) => a + b; // C# 3.0 lambda,2.0 需用匿名方法
IAsyncResult ar = c.BeginInvoke(1, 2, CallbackMethod, null);

其他實用特性

特性語法用途
屬性存取修飾詞public string Name { get; protected set; }分離讀寫可見性
靜態類別public static class Utility { }編譯器強制僅含靜態成員、不可實例化、不可繼承
全域命名空間限定::System.Console.WriteLine()解決巢狀命名空間衝突
區域警告控制#pragma warning disable 169精確抑制特定警告
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved