delegate 声明定义一种引用类型,该类型可用于将方法用特定的签名封装。委托实例封装静态方法或实例方法。委托大致类似于 C++ 中的函数指针;但是,委托是类型安全和可靠的。
声明采用下列形式:
[attributes] [modifiers] delegate result-type identifier ([formal-parameters]);
其中:
-
attributes(可选)
- 附加的声明性信息。 modifiers(可选)
- 允许使用的修饰符有new 和四个访问修饰符。 result-type
- 同方法的返回类型匹配的结果类型。 identifier
- 委托名称。 formal-parameters(可选)
- 参数列表。如果参数是一个指针,则必须用unsafe修饰符声明委托。
备注
委托使您得以将函数作为参数传递。委托的类型安全要求作为委托传递的函数拥有同委托声明相同的签名。请参见委托教程了解有关使用委托的更多信息。
“委托教程”显示了如何撰写委托,即如何从其他委托创建委托。不能撰写包含out 参数的委托。
委托是事件的基础。
有关委托的更多信息,请参见 15. 委托。
示例 1
以下是声明及使用委托的一个简单示例。
// keyword_delegate.cs // delegate declaration delegate void MyDelegate(int i); class Program { public static void Main() { TakesADelegate(new MyDelegate(DelegateFunction)); } public static void TakesADelegate(MyDelegate SomeFunction) { SomeFunction(21); } public static void DelegateFunction(int i) { System.Console.WriteLine("Called by delegate with number: {0}.", i); } }
输出
Called by delegate with number: 21.
示例 2
在下例中,一个委托被同时映射到静态方法和实例方法,并分别返回特定的信息。
// keyword_delegate2.cs // Calling both static and instance methods from delegates using System; // delegate declaration delegate void MyDelegate(); public class MyClass { public void InstanceMethod() { Console.WriteLine("A message from the instance method."); } static public void StaticMethod() { Console.WriteLine("A message from the static method."); } } public class MainClass { static public void Main() { MyClass p = new MyClass(); // Map the delegate to the instance method: MyDelegate d = new MyDelegate(p.InstanceMethod); d(); // Map to the static method: d = new MyDelegate(MyClass.StaticMethod); d(); } }
输出
A message from the instance method. A message from the static method.