usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Reflection;usingSystem.Linq.Expressions;namespaceinpexone.learncs{classRefletlambdadelegate {Static Object[] Parameters =New Object[] {1,2 }; Public Delegate intAddDelegate (intAintb); Public intAddintAintb) {returnA +b; } Public Static voidMain () {refletlambdadelegate rld=Newrefletlambdadelegate (); //call the Add method with reflection.MethodInfo add =typeof(refletlambdadelegate). GetMethod ("Add"); Console.WriteLine ("The add result from using the reflection is: {0}", Add. Invoke (rld, parameters)); //call the Add method with the lambda expression tree.expression<func<int,int,int>> Extree = (A, b) = =Rld.add (A, b); Func<int,int,int> delinstance =Extree.compile (); intresult = Delinstance (int. Parse (parameters[0]. ToString ()),int. Parse (parameters[1]. ToString ())); Console.WriteLine ("The add result from using the Lambdatree is: {0}", result); //invokes the Add method with a lambda expression.func<int,int,int> Addlambda = (c, d) = =Rld.add (c, D); intRESULT1 = Addlambda (int. Parse (parameters[0]. ToString ()),int. Parse (parameters[1]. ToString ())); Console.WriteLine ("The add result from using the Lambda without tree is: {0}", RESULT1); //invokes the Add method with a delegate.AddDelegate adddelgateinstance =Newadddelegate (Rld.add); intRESULT2 = Adddelgateinstance (int. Parse (parameters[0]. ToString ()),int. Parse (parameters[1]. ToString ())); Console.WriteLine ("The add result from using the delegate is: {0}", RESULT2); //call the Add method with an anonymous method.AddDelegate anonymousinstance =Delegate(intAintb) {returnRld.add (A, b);}; intRESULT3 = Anonymousinstance (int. Parse (parameters[0]. ToString ()),int. Parse (parameters[1]. ToString ())); Console.WriteLine ("The add result from using the anonymous method is: {0}", RESULT3); Console.ReadLine (); } }}
The above code compares the procedures for delegates, anonymous methods, lambda expressions, lambda expression trees, and reflection to perform the same method, with the output being:
The process of executing the same method on delegates, anonymous methods, lambda expressions, lambda expression trees, and reflections is compared in C #, respectively.