C # lambda operator =) anonymous method lambda expression
Lambda expressions are anonymous functions and are new features introduced in C #3.0. Lambda operator =>, which is read as "goes ". C # provides a mechanism for delegation to define anonymous parties for the delegation
Method. If the anonymous method does not have a name, the compiler will specify a name. In an anonymous method, you cannot use a jump statement to jump to the external side of the anonymous method or to the internal side of the method. It cannot be external to the anonymous method.
The ref and out parameters used.
The following code demonstrates a Lambda expression:
Using System; using System. collections. generic; using System. linq; using System. text; using System. linq. expressions; // usingnamespace Lambda {class Program {// delegate method delegate string MyDelagate (string val); static void Main (string [] args) {string str1 = "anonymous external Method \ n"; // a method is defined in brackets without a name. The Compiler automatically specifies a name named MyDelagate my = (string param) ==>{ string str2 = "internal anonymous Method \ n"; return (param + str1 + str2) ;}; // call the entrusted anonymous method Console. writeLine (my ("Parameter \ n"); // you can see from the result that the anonymous method achieves the same effect as the delegate-defined entity method Console. read ();}}}
Lambda operator =>
Parameters on the left, expressed in parentheses(String param ),
The right side is the implementation code, which uses curly brackets. If the Code has only one line, you can use no curly brackets or the return keyword. the compiler will add them to us.
This is a simple implementation of the lambda expression:
String str1 = "external anonymous method"; string str2 = "internal anonymous method"; MyDelagate my = param => param + str1 + str2; Console. writeLine (my ("parameter "));
1 parameter:
private delegate int MyDelagate(int i);MyDelagate test1 = x => x * x;MyDelagate test2 = (x) => x * x;MyDelagate test3 = (int x) => x * x;MyDelagate test4 = (int x) => { return x * x; };Console.WriteLine(test1(10));Console.WriteLine(test2(10));Console.WriteLine(test3(10));Console.WriteLine(test4(10));
Two or more parameters: Two or more parameters cannot be written in a simple way, and must be declared in parentheses.
private delegate int MyDelagate(int x, int y);MyDelagate test1 = (x, y) => x * y;MyDelagate test2 = (int x, int y) => x * y;MyDelagate test3 = (int x, int y) => { return x * y; };Console.WriteLine(test1(3,4));Console.WriteLine(test2(3,4));Console.WriteLine(test3(3,4));
No parameter:
private delegate void Void(); void test11 = () => { Console.WriteLine("Void Params"); }; test11();