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!"); };

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.

从 C# 9.0 开始,可以使用弃元指定该方法不使用的两个或更多个匿名方法输入参数:Beginning with C# 9.0, you can use discards to specify two or more input parameters of an anonymous method that aren't used by the method:

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

为实现向后兼容性,如果只有一个参数名为 _,则将 _ 视为匿名方法中该参数的名称。For backwards compatibility, if only a single parameter is named _, _ is treated as the name of that parameter within an anonymous method.

从 C# 9.0 开始,可以在匿名方法的声明中使用 static 修饰符:Also beginning with C# 9.0, you can use the static modifier at the declaration of an anonymous method:

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

静态匿名方法无法从封闭范围捕获局部变量或实例状态。A static anonymous method can't capture local variables or instance state from enclosing scopes.

还可以使用 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