Anonymous functions: Lambda expressions, anonymous methods, and lambda expressions
An "inline" statement or expression of an anonymous function, which can be used wherever the delegate type is required. You can use an anonymous function to initialize the name delegate, or pass the name delegate (instead of the name delegate type) as the method parameter.
There are two types of anonymous functions:
Lambda expressions (here we will only apply the Lambda expressions in the delegate)
Anonymous Method
Lambda expressions are anonymous functions that can be used to create a delegate or expression directory tree (discussed later. By using Lambda expressions, you can write local functions that can be passed as parameters or returned as function call values.
To create a Lambda expression, specify the input parameter on the left side of the Lambda operator => (if any), and then enter the expression or statement block on the other side.
Let's look at an example:
Delegate int del (int I); static void Main (string [] args) {// Lambda expression used to create a delegate del myDelegate = x => x * x; int j = myDelegate (5); Console. writeLine (j );}
(Input parameters) => expression
Parentheses are optional only when Lambda has only one input parameter; otherwise, parentheses are required. Two or more input parameters in parentheses are separated by commas:
(X, y) => x = y
Sometimes, the compiler is difficult or unable to deduce the input type. In this case, you can display the specified type:
(Int x, string s) => s. length> x
Use parentheses to specify the following parameters:
() => SomeMethod ()
Statement Lambda
The statement Lamdba is similar to the Lambda expression, but the statement is enclosed in braces:
(Input parameters) =>{ statement ;}
Let's look at an example:
Delegate void TestDelegate (string s); static void Main (string [] args) {// Lambda statement is used to create a delegate TestDelegate myDel = n => {string s = n + "" + "World"; Console. writeLine (s) ;}; myDel ("Hello ");}
Anonymous Method
In C # versions earlier than 2.0, the only way to declare a delegate is to use the naming method. C #2.0 introduces anonymous methods. In C #3.0 and later versions, Lambda expressions replace anonymous methods as the first way to write Inline code.
Let's look at an example:
Delegate void Printer (string s); static void Main (string [] args) {// delegate and anonymous Method Association Printer p = delegate (string st) {Console. writeLine (st) ;}; p ("The delegate using the anonymous method is called. "); // The delegate is associated with the naming method p = new Printer (DoWork); p (" The delegate using the named method is called. "); Console. readKey ();} static void DoWork (string k) {Console. writeLine (k );}