As we have mentioned, delegation is used to reference methods with the same label as it. In other words, you can use the delegate object to call methods that can be referenced by the delegate.
C # Anonymous method
As we have mentioned, delegation is used to reference methods with the same label as it. In other words, you can use the delegate object to call methods that can be referenced by the delegate.
The Anonymous method (Anonymous methods) provides a technique for passing code blocks as delegate parameters. The anonymous method has no subject name.
In an anonymous method, you do not need to specify the return type. it is inferred from the return statement in the method body.
Syntax for writing anonymous methods
The anonymous method is declared by using the delegate keyword to create a delegated instance. For example:
delegate void NumberChanger(int n);...NumberChanger nc = delegate(int x){ Console.WriteLine("Anonymous Method: {0}", x);};
Code block Console. WriteLine ("Anonymous Method: {0}", x); is the subject of Anonymous methods.
A delegate can be called by using an anonymous method or a naming method, that is, passing method parameters to the delegate object.
For example:
nc(10);
Instance
The following example demonstrates the concept of an anonymous method:
Using System; delegate void NumberChanger (int n); namespace DelegateAppl {class TestDelegate {static int num = 10; public static void AddNum (int p) {num + = p; Console. writeLine ("Named Method: {0}", num);} public static void MultNum (int q) {num * = q; Console. writeLine ("Named Method: {0}", num);} public static int getNum () {return num;} static void Main (string [] args) {// use the anonymous method to create the delegated instance NumberChanger nc = delegate (int x) {Console. writeLine ("Anonymous Method: {0}", x) ;}; // call the delegate nc (10) using an Anonymous Method ); // use the naming method to instantiate the delegate nc = new NumberChanger (AddNum); // use the naming method to call the delegate nc (5 ); // use another naming method to instantiate the delegate nc = new NumberChanger (MultNum); // use the naming method to call the delegate nc (2); Console. readKey ();}}}
When the code above is compiled and executed, it will produce the following results:
Anonymous Method: 10Named Method: 15Named Method: 30
The above is the content of the [c # tutorial] C # Anonymous method. For more information, see PHP Chinese website (www.php1.cn )!