C#中分别对委托、匿名方法、Lambda表达式、Lambda表达式树以及反射执行同一方法的过程进行比较。...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Linq.Expressions;

namespace INPEXOne.LearnCS
{
    class RefletLambdaDelegate
    {
        static object[] parameters = new object[] { 1, 2 };
        public delegate int addDelegate(int a, int b);

        public int add(int a ,int b) 
        {
            return a + b;
        }

        public static void Main() 
        {
            RefletLambdaDelegate rld=new RefletLambdaDelegate();       
            //利用反射调用add方法.
            MethodInfo add = typeof(RefletLambdaDelegate).GetMethod("add");
            Console.WriteLine("The add result from using the reflection is : {0}",add.Invoke(rld, parameters));

            //利用Lambda表达式树调用add方法.
            Expression<Func<int, int, int>> extree = (a,b) => rld.add(a, b);
            Func<int, int, int> delinstance = extree.Compile();
            int result = delinstance(int.Parse(parameters[0].ToString()), int.Parse(parameters[1].ToString()));
            Console.WriteLine("The add result from using the LambdaTree is : {0}",result);

            //利用Lambda表达式调用add方法.
            Func<int, int, int> addLambda = (c, d) => rld.add(c, d);
            int result1 = 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);

            //利用委托调用add方法.
            addDelegate addDelgateInstance = new addDelegate(rld.add);
            int result2 = addDelgateInstance(int.Parse(parameters[0].ToString()), int.Parse(parameters[1].ToString()));
            Console.WriteLine("The add result from using the delegate is : {0}", result2);

            //利用匿名方法调用add方法.
            addDelegate AnonymousInstance = delegate(int a, int b) { return rld.add(a,b); };
            int result3 = 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();
        }
    }
}

以上代码分别对委托、匿名方法、Lambda表达式、Lambda表达式树以及反射执行同一方法的过程进行比较,输出结果为:

转载于:https://www.cnblogs.com/LanTianYou/p/4439260.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值