委托、多播委托、泛型委托Func,Action,Predicate,ExpressionTree

当试图通过一个事件触发多个方法,抽象出泛型行为的时候,或许可以考虑使用委托。

 

  通过委托构造函数或委托变量把方法赋值给委托

        private delegate double DiscountDelegate(double discount);
        private static DiscountDelegate dd = getDiscountRate;
        static void Main(string[] args)
        {
            double discountPercent;
            discountPercent = dd.Invoke(80);
            Console.WriteLine("打折比例是{0}",discountPercent);
 
            DiscountDelegate dd1 = new DiscountDelegate(getDiscountRate);
            discountPercent = dd1(90);
            Console.WriteLine("打折比例是{0}", discountPercent);
            Console.ReadKey();
        }
 
        static double getDiscountRate(double discount)
        {
            return (discount/100);
        }

 

  多播委托

        private delegate double CalculateDelegate(double x, double y);
        private static CalculateDelegate cd = getPlus;
 
        static void Main(string[] args)
        {
            double result1 = cd.Invoke(1, 2);
            Console.WriteLine(result1);
            cd += new CalculateDelegate(getMinus);
            double result2 = cd.Invoke(1, 2);
            Console.WriteLine(result2);
            Console.ReadKey();
        }
 
        static double getPlus(double x, double y)
        {
            return (x + y);
        }
 
        static double getMinus(double x, double y)
        {
            return (x - y);
        }

 

  泛型委托

□ Func<>规定输入输出的泛型委托

    Func<Calculate, double> func = c => c.X*3 + c.Y;
    Calculate calculate = new Calculate(){X = 2,Y=3};
    double result = func(calculate);
    Console.WriteLine(result);
 
    class Calculate
    {
        public double X { get; set; }
        public double Y { get; set; }
    }       

 

□ Action<>规定输入的泛型委托

    ction<string> MyAction = x => Console.WriteLine(x);
     MyAction("Hello World");    

 

□ Predicate<>规定输出为bool类型的泛型委托

   string date = "2012/05/10";
    Predicate<string> isDate = d => IsDate(d);
    if (isDate(date))
    {
        Console.WriteLine("有效");
    }
    else
    {
        Console.WriteLine("无效");
    }
 
    private static bool IsDate(string date)
    {
        DateTime dt;
        return DateTime.TryParse(date, out dt);
    }   
 

 

□ ExpressionTree泛型委托

    //(5+4)-(2-1)
    //5+4
    BinaryExpression exp1 = Expression.MakeBinary(ExpressionType.Add, Expression.Constant(5),Expression.Constant(4));
    //2-1
    BinaryExpression exp2 = Expression.MakeBinary(ExpressionType.Subtract, Expression.Constant(2),Expression.Constant(1));
 
    //(5+4)-(2-1)
    BinaryExpression resultExp = Expression.MakeBinary(ExpressionType.Subtract, exp1, exp2);
    int result = Expression.Lambda<Func<int>>(resultExp).Compile()();
    Console.WriteLine(result);
    Console.ReadKey();     
posted @ 2014-05-14 10:53  Darren Ji  阅读(475)  评论(0编辑  收藏  举报

我的公众号:新语新世界,欢迎关注。