C#中委托(delegate)是一种安全地封装方法的类型,委托是面向对象的、类型安全的。
使用委托的步骤:
1、声明委托
public delegate void DelegateHandler(string message);
2、定义委托方法
// Create a method for a delegate. public static void DelegateMethod(string message) { Console.WriteLine(message); }
3、创建委托对象,并将需要传递的函数作为参数传入
// Instantiate the delegate. DelegateHandler handler = DelegateMethod;
或:
// Instantiate the delegate. DelegateHandler handler = new DelegateHandler(DelegateMethod);
4、调用委托方法
// Call the delegate. handler("Hello World");
完整示例:
using System; using System.Collections.Generic; using System.Text; namespace DelegateExample { class Program { public delegate void DelegateHandler(string message); public static void DelegateMethod(string message) { Console.WriteLine(message); } static void Main(string[] args) { //DelegateHandler handler = DelegateMethod; DelegateHandler handler = new DelegateHandler(DelegateMethod); handler("Hello World!"); } } }