[C#] 委托delegate

delegate

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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值