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

C# 5 in a Nutshell - Delegate

时间:2015-02-06 11:09:33      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

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; }
}

 

C# 5 in a Nutshell - Delegate

标签:

原文地址:http://www.cnblogs.com/davidgu/p/4276540.html

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