delegate(委托)的用法

来源:互联网 发布:哈尔滨linux运维招聘 编辑:程序博客网 时间:2024/05/18 02:57

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
原创粉丝点击