delegate(委托)的用法

https://msdn.microsoft.com/zh-cn/library/ms173172.aspx

delegate是安全封装方法的一个类型,类似于C的函数指针,但是delegate是面像对象,功能比函数指针更丰富。Delegate 类型派生自.Net Framework的Delegate类,是封装的,不能够派生出其他类,也不能从Delegate class中派生出自定义类。

1、Delegate是一个对象,可以作为参数或被分配给一个属性。作为参数传给另一个函数时,可用作为异步调用的回调函数中。



	public delegate void Del(string message);
public static void DelegateMethod(string message)
{
    System.Console.WriteLine(message);
}
Del handler = DelegateMethod;

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

2、multicasting(多播)。要形成the invocation list(调用列表),可直接利用 "+“ ”-“操作符,比如allMethodDelegate将会依次调用d1,d2,d3函数。

public class MethodClass
{
    public void Method1(string message) { }
    public void Method2(string message) { }
}
MethodClass obj = new MethodClass();
Del d1 = obj.Method1;
Del d2 = obj.Method2;
Del d3 = DelegateMethod;

//Both types of assignment are valid.
Del allMethodsDelegate = d1 + d2;
allMethodsDelegate += d3;
 3、Delegate派生自 
  
System.Delegate 
,所以可以利用该类中的属性,比如可查看到invocation list的长度。 

int invocationCount = d1.GetInvocationList().GetLength(0);
4、Multcast delegates(多播委托)广泛应用于事件处理中。

Multicast delegates are used extensively in event handling. Event source objects send event notifications to recipient objects that have registered to receive that event. To register for an event, the recipient creates a method designed to handle the event, then creates a delegate for that method and passes the delegate to the event source. The source calls the delegate when the event occurs. The delegate then calls the event handling method on the recipient, delivering the event data. The delegate type for a given event is defined by the event source.
源事件中定义委托,接受事件对象创建事件处理方法和创建委托,并将委托传递给源事件。在事件发生时,源事件调用委托,然后委托在接受事件对象中调用事件处理方法,传递事件数据。
Remarks:以上4点用到的是带命名方法的delegate,属于早期C#使用,delegate不区别static method 或者instance method,只直接引用method,但要注意的是两者定义类型一定要一样。带有匿名方法的delegate,使用lambda expressions

public delegate void Del(string message);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值