[C # Basics] c # Lambda expressions
Today, when I read other people's code, I found this -- "=>", which looks like a pointer in the C language, and also like this expression -- ":)", no matter what it looks like, it really stumped me, so I decided to study it.
Simply put, Lambda expressions are like Anonymous delegates.
Using UnityEngine; using System. collections; // to create a Lambda expression, specify the input parameter (if any) on the left side of the Lambda operator => and then enter the expression or statement block on the other side. // Parentheses are optional only when lambda has only one input parameter; otherwise, parentheses are required. // Two or more input parameters in the brackets are separated by commas (,). public class TestCSharp: MonoBehaviour {delegate void TestDelegate (); delegate void TestDelegate2 (string s ); delegate void TestDelegate3 (string m, string n); delegate int TestDelegate4 (int I); // Use this for initializationvoid Start () {// => the right side is the statement block, can contain any number of statements TestDelegate testDelA = () => {print ("start testing! "); Print (" Are you ready? ") ;}; TestDelegate2 testDelB = (x) =>{ print (x) ;}; TestDelegate3 testDelC = (x, y) ==>{ print (x + y) ;}; testDelA (); testDelB ("HelloWorld"); testDelC ("world", "hello "); // => Expression TestDelegate4 testDelD = x => x * 11; int j = testDelD (8); // j = 88 print (j ); // => method TestDelegate testDelE = () => TestA (); testDelE (); TestDelegate testDelF = () => TestB (); testDelF + = () => TestC (); testDelF (); TestD (() => TestB (), () => TestC ();} void TestA () {print ("goodbye! ");} Void TestB () {print (" Ah! ");} Void TestC () {print (" I'm back! ");} Void TestD (TestDelegate a, TestDelegate B) {a (); B ();}}
Running result:
In the TestD method, Lambda expressions are passed directly to a delegate when the parameter is passed, you know ..
In addition, the explanation on msdn is quite detailed. Click here to transfer it ..