anonymous method
The anonymous method is an advanced feature introduced in. NET 2.0, and the word "anonymous" indicates that it can write the implementation inline in a method to form a delegate object without having an explicit method name, such as:
static void Test()
{
Action<string> action = delegate(string value)
{
Console.WriteLine(value);
};
action("Hello World");
}
But the key to anonymous methods is not just the word "anonymous". The most powerful feature is that the anonymous method forms a closure that can be passed as an argument to another method, but it can also access local variables of the method and other members of the current class. For example:
class TestClass
{
private void Print(string message)
{
Console.WriteLine(message);
}
public void Test()
{
string[] messages = new string[] { "Hello", "World" };
int index = 0;
Action<string> action = (m) =>
{
this.Print((index++) + ". " + m);
};
Array.ForEach(messages, action);
Console.WriteLine("index = " + index);
}
}
As shown above, in the TestClass test method, the action delegate invokes the private method print in the TestClass class and reads and writes the local variable index in the test method. In addition to the new features of lambda expressions in C # 3.0, the use of anonymous methods has been greatly promoted. However, if used improperly, anonymous methods can easily cause problems that are difficult to discover.