什么是C#匿名方法? [英] What are anonymous methods in C#?
问题描述
有人能解释一下匿名方法是C#(在简单计算),并提供可能的例子,请
Could someone explain what anonymous methods are in C# (in simplistic terms) and provide examples in possible please
推荐答案
匿名方法被引入到C#2为,而无需编写一个单独的方法创建委托实例的方法。他们可以的捕捉的封闭的方法中的局部变量,使他们的一种形式的关闭的。
Anonymous methods were introduced into C# 2 as a way of creating delegate instances without having to write a separate method. 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, e.g. 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:
- 在我的上委托变化的文章(写了很久以前),在C#2
- MSDN上的匿名方法
- 的 C#第5章深度如果你喜欢买我的书:)
- My article (written a long time ago) on delegate changes in C# 2
- MSDN on anonymous methods
- Chapter 5 of C# in Depth if you fancy buying my book :)
需要注意的是lamdba EX pressions在C#3具有的几乎的完全取代匿名方法(虽然他们仍然是完全有效的,当然)。匿名方法和lambda EX pressions都被统称为的匿名函数的。
Note that lamdba expressions in C# 3 have almost completely replaced anonymous methods (although they're still entirely valid of course). Anonymous methods and lambda expressions are collectively described as anonymous functions.
这篇关于什么是C#匿名方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!