简体   繁体   English

C#中的匿名方法是什么?

[英]What are anonymous methods in C#?

有人可以解释一下C#中的匿名方法(简单来说),并提供可能的例子

Anonymous methods were introduced into C# 2 as a way of creating delegate instances without having to write a separate method. 匿名方法被引入到C#2中,作为创建委托实例的一种方式,而无需编写单独的方法。 They can capture local variables within the enclosing method, making them a form of closure . 它们可以在封闭方法中捕获局部变量,使它们成为闭包形式。

An anonymous method looks something like: 匿名方法看起来像:

delegate (int x) { return x * 2; }

and must be converted to a specific delegate type, eg via assignment: 并且必须转换为特定的委托类型,例如通过赋值:

Func<int, int> foo = delegate (int x) { return x * 2; };

... or subscribing an event handler: ...或订阅事件处理程序:

button.Click += delegate (object sender, EventArgs e) {
    // React here
};

For more information, see: 有关更多信息,请参阅:

Note that lamdba expressions in C# 3 have almost completely replaced anonymous methods (although they're still entirely valid of course). 请注意,C#3中的lamdba表达式几乎完全取代了匿名方法(尽管它们当然仍然完全有效)。 Anonymous methods and lambda expressions are collectively described as anonymous functions . 匿名方法和lambda表达式统称为匿名函数

Anonymous method is method that simply doesn't have name and this method is declared in place, for example: 匿名方法是简单地没有名称的方法,并且此方法是在适当的位置声明的,例如:

Button myButton = new Button();
myButton .Click +=
delegate
{
    MessageBox.Show("Hello from anonymous method!");
};

An anonymous method is a block of code that is used where a method would usually be required and which does not have a name (hence anonymous). 匿名方法是一个代码块,用于通常需要方法且没有名称的方法(因此是匿名的)。

MSDN has examples of using anonymous methods . MSDN有使用匿名方法的示例

These are methods without name. 这些是没有名字的方法。

For example, ordinary method is: 例如,普通方法是:

public void Foo()
{
   Console.WriteLine("hello");
}

While anonymous method can be: 虽然匿名方法可以是:

myList.ForEach(item => Console.WriteLine("Current item: " + item));

The code inside the ForEach is actually a method but has no name and you can't call it from the outside. ForEach的代码实际上是一个方法但没有名称,你不能从外面调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM