C # Anonymous Methods
As we have already mentioned, a delegate is used to refer to a method that has the same label as it. In other words, you can use a delegate object to invoke a method that can be referenced by a delegate.
The anonymous method (Anonymous methods) provides a technique for passing code blocks as delegate parameters. An anonymous method is a method that has no name but a principal.
In an anonymous method, you do not need to specify a return type, which is inferred from the return statement within the method body.
Syntax for writing anonymous methods
The anonymous method is declared by creating a delegate instance using the Delegate keyword. 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 body of the anonymous method.
Delegates can be called by anonymous methods, or by named methods, that is, by 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 anonymous method to create delegate instance Numberchanger NC = delegate (int x) {Console.WriteLine ("Anonymous Method: {0}", x); }; The delegate NC (10) is invoked using an anonymous method; Instantiating a delegate using a named method NC = new Numberchanger (addnum); Call the delegate NC (5) using the named method; Instantiate a delegate using another named method NC = new Numberchanger (multnum); Call the delegate NC (2) using the named method; Console.readkey (); } }}
When the above code is compiled and executed, it produces the following results:
Anonymous method:10named method:15named method:30
The above is the "C # Tutorial" C # anonymous method of content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!