Anonymous methods is one of the new features of C #2.0, which allows us Code Create a built-in method without a method name and associate the Code with the delegated instance. This makes the delegation instantiation more intuitive and convenient, and improves the readability and maintainability of the Code. The following describes how to use a simple anonymous method:
Private Int [] _ Integers = {1,2,3,4,5,6,7,8,9,10} ;
Int [] Evenintegers = Array. findall (_ integers, Delegate ( Int Integer)
{
Return(Integer%2 = 0);
}
);
The code above uses the anonymous method to obtain the number of divisible by 2 in the array. The anonymous method is:
Delegate ( Int Integer)
{
Return(Integer%2 = 0);
}
If we do not need anonymous methods, we need to create a specific method, as shown below:
Private Int [] _ Integers = {1,2,3,4,5,6,7,8,9,10} ;
Int [] Evenintegers = Array. findall (_ integers, iseven );
Private Bool Iseven ( Int Integer)
{
Return(Integer%2 = 0);
}
The anonymous method is used in the case that the method is relatively simple and will not be called elsewhere. We can also use the anonymous method as follows:
Button1.click + =
Delegate
{
MessageBox. Show ("Hello");
} ;