首页 > Windows开发 > 详细

C# 5 in a Nutshell - Delegate

时间:2015-02-06 11:08:18      阅读:291      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!