C# 5 in a Nutshell - Delegate

1. What is delegate in C#?

A delegate is an object that knows how to call a method.
A delegate type defines the kind of method that delegate instances can call. Specifically,
it defines the method’s return type and its parameter types.

The followingdefines a delegate type called Transformer:
delegate int Transformer (int x);

 Transformer is compatible with any method with an int return type and a single
int parameter, such as this:
static int Square (int x) { return x * x; }
Assigning a method to a delegate variable creates a delegate instance:
Transformer t = Square;

 

complete code:

public delegate int Transformer (int x);
class Util
{
    public static void Transform (int[] values, Transformer t)
    {
        for (int i = 0; i < values.Length; i++)
        values[i] = t (values[i]);
    }
}

class Test
{
    static void Main()
    {
        int[] values = { 1, 2, 3 };
        Util.Transform (values, Square); // Hook in the Square method
        foreach (int i in values)
        Console.Write (i + " "); // 1 4 9
    }
    static int Square (int x) { return x * x; }
}

 

posted @ 2015-02-06 10:28  Master HaKu  阅读(469)  评论(0编辑  收藏  举报