首页 > 代码库 > c# delegate

c# delegate

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