C#委托

来源:互联网 发布:hive 数组 contains 编辑:程序博客网 时间:2024/05/01 20:56

委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。委托方法的调用可以像其他任何方法一样,具有参数和返回值,如下面的示例所示

 

public delegate void Del(string message);

 

// Create a method for a delegate.
public static void DelegateMethod(string message)
{
    System.Console.WriteLine(message);
}

 

// Instantiate the delegate.
Del handler = DelegateMethod;

// Call the delegate.
handler("Hello World");

 

 

回调的另一个常见用法是定义自定义的比较方法并将该委托传递给排序方法。它允许调用方的代码成为排序算法的一部分。下面的示例方法使用 Del 类型作为参数:

 

public void MethodWithCallback(int param1, int param2, Del callback)
{
    callback("The number is: " + (param1 + param2).ToString());
}

 

MethodWithCallback(1, 2, handler);

 

在控制台中将收到下面的输出:

The number is: 3

原创粉丝点击