开发者

What are anonymous methods in C#?

开发者 https://www.devze.com 2023-03-06 13:08 出处:网络
Coul开发者_StackOverflowd someone explain what anonymous methods are in C# (in simplistic terms) and provide examples in possible pleaseAnonymous methods were introduced into C# 2 as a way of creating

Coul开发者_StackOverflowd someone explain what anonymous methods are in C# (in simplistic terms) and provide examples in possible please


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:

  • 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 :)

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消