共用方式為


delegate 運算子

運算子 delegate 會建立可以轉換成委派類型的匿名方法。 匿名方法可以轉換成型別,例如 System.ActionSystem.Func<TResult> 做為許多方法自變數的類型。

Func<int, int, int> sum = delegate (int a, int b) { return a + b; };
Console.WriteLine(sum(3, 4));  // output: 7

備註

Lambda 表達式提供更簡潔且具表達性的方式來建立匿名函式。 使用 => 運算符 來建構 Lambda 運算式:

Func<int, int, int> sum = (a, b) => a + b;
Console.WriteLine(sum(3, 4));  // output: 7

如需 Lambda 運算式功能的詳細資訊,例如擷取外部變數,請參閱 Lambda 運算式

當您使用 delegate 運算子時,可能會省略參數清單。 如果您這樣做,建立的匿名方法可以轉換成具有任何參數清單的委派類型,如下列範例所示:

Action greet = delegate { Console.WriteLine("Hello!"); };
greet();

Action<int, double> introduce = delegate { Console.WriteLine("This is world!"); };
introduce(42, 2.7);

// Output:
// Hello!
// This is world!

這是 lambda 表達式不支援的匿名方法唯一功能。 在其他所有情況下,Lambda 表達式是撰寫內嵌程式代碼的慣用方法。 您可以使用 捨棄 來指定方法未使用之匿名方法的兩個或多個輸入參數:

Func<int, int, int> constant = delegate (int _, int _) { return 42; };
Console.WriteLine(constant(3, 4));  // output: 42

為了回溯相容性,如果只將單一參數命名 _為 , _ 則會被視為匿名方法內的該參數名稱。

您可以在匿名方法的宣告中使用 static 修飾詞:

Func<int, int, int> sum = static delegate (int a, int b) { return a + b; };
Console.WriteLine(sum(10, 4));  // output: 14

靜態匿名方法無法從封入範圍擷取局部變數或實例狀態。

您也可以使用 delegate 關鍵詞來宣告 委派類型

編譯器可以快取從方法群組建立的代理物件。 請考慮下列方法:

static void StaticFunction() { }

當你將方法群組指派給代理時,編譯器會快取該代理:

Action a = StaticFunction;

C# 語言規格

如需詳細資訊,請參閱C# 語言規格的 Anonymous 函式運算式 一節。

另請參閱