delegate 運算子 (C# 參考)delegate operator (C# reference)

delegate 運算子會建立可轉換成委派型別的匿名方法:The delegate operator creates an anonymous method that can be converted to a delegate type:

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

注意

從 C# 3 開始,Lambda 運算式提供更精簡且更具表達性的方式來建立匿名函式。Beginning with C# 3, lambda expressions provide a more concise and expressive way to create an anonymous function. 使用 => 運算子來建構 Lambda 運算式:Use the => operator to construct a lambda expression:

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

如需 Lambda 運算式功能的詳細資訊 (例如,捕捉外部變數),請參閱 Lambda 運算式For more information about features of lambda expressions, for example, capturing outer variables, see Lambda expressions.

當您使用 delegate 運算子時,您可以省略參數清單。When you use the delegate operator, you might omit the parameter list. 如果您這樣做,則可以將建立的匿名方法轉換成含任何參數清單的委派型別,如下列範例所示:If you do that, the created anonymous method can be converted to a delegate type with any list of parameters, as the following example shows:

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 運算式不支援的唯一匿名方法功能。That's the only functionality of anonymous methods that is not supported by lambda expressions. 在所有其他情況下,建議您以 Lambda 運算式的方式來撰寫內嵌程式碼。In all other cases, a lambda expression is a preferred way to write inline code.

您也可以使用 delegate 關鍵字來宣告委派型別You also use the delegate keyword to declare a delegate type.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格匿名函式運算式一節。For more information, see the Anonymous function expressions section of the C# language specification.

另請參閱See also