码迷,mamicode.com
首页 > Windows程序 > 详细

c# delegate

时间:2017-04-29 17:33:20      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:asi   tin   version   bsp   anti   ted   instant   cep   ati   

C# version 1.0 delegate

// Declare delegate type PerformCalculator
public delegate int PerformCalculator(int x, int y);

public class SampleClass
{
    private int Add(int x, int y) {
        return x + y;
    }

    private int Minus(int x, int y)
    {
        return x - y;
    }

    public int DoCalculate(string type, int x, int y)
    {
        // Create PerformCalculator instance
        PerformCalculator add = new PerformCalculator(Add);
        PerformCalculator minus = new PerformCalculator(Minus);
        if (type == "add")
            // Execute delegate
            return add(x, y);
        else
            return minus(x, y);
    }
}

C# version 2.0 introduced anonymous method, creating anonymous methods is essentially a way to pass a code block as a delegate paramater.

    // Declare delegate type PerformCalculator
    public delegate int PerformCalculator(int x, int y);

    public class Delegate
    {public int DoCalculate(string type, int x, int y)
        {
            // Create PerformCalculator instance
            PerformCalculator add = delegate(int dx, int dy) { return dx + dy; };
            PerformCalculator minus = delegate(int dx, int dy) { return dx - dy; };
            if (type == "add")
                // Execute delegate
                return add(x, y);
            else
                return minus(x, y);
        }
    }

C# 3.0 introduced lambda expressions, which are similar in concept to anonymous methods but more expressive and concise. 

    // Declare delegate type PerformCalculator
    public delegate int PerformCalculator(int x, int y);

    public class Delegate
    {
        public int DoCalculate(string type, int x, int y)
        {
            // Create PerformCalculator instance
            PerformCalculator add = (dx, dy) => dx + dy;
            PerformCalculator minus = (dx, dy) => dx - dy;
            if (type == "add")
                // Execute delegate
                return add(x, y);
            else
                return minus(x, y);
        }
    }

Delegates are the basis for Events.

The delegate must be instantiated with a method or lamda expression that has a compatiable return type and input parameter.

c# delegate

标签:asi   tin   version   bsp   anti   ted   instant   cep   ati   

原文地址:http://www.cnblogs.com/liangzi4000/p/6784114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!