delegate and event

以前在c里面都说函数指针指向了哪个函数,现在说那些函数连接到了这个代理,因为c里面的指针一次只能指向一个函数,但是代理可以指向多个函数的入口地址。

// declares a delegate for a method that takes a single
//  argument of type string and has a void return type
delegate void MyDelegate1(string s);

声明代理的时候,在编译的时候声明了一个类

// instantiating a delegate to a static method Hello
//   in the class MyClass
MyDelegate1 a = new MyDelegate1(MyClass.Hello);

// instantiating a delegate to an instance method
//  AMethod in object p
MyClass p = new MyClass();
MyDelegate1 b = new MyDelegate1(p.AMethod);

// given the previous delegate declaration and
//  instantiation, the following invokes MyClass'
//  static method Hello with the parameter "World"
a("World");

a = a + b;
a("World");
这样就可以实现顺序调用两个事件MyClass.Hello(“World”) , p.AMethod("World").

a = a -b;
a("World");
又回到原来的MyClass.Hello(“World”)

Multicast Delegates(多波代理)

引用多个方法的委托,它连续调用每个方法,委托必须是同类型的,返回类型必须是void,不可以带输出参数(可以带引用参数)。多波代理应用于事件模型中

All Delegates Have an Invocation List of Methods That Are
 
 
Executed When Their Invoke Method is Called

Single-Cast Delegates: Derived Directly From System.MulticastDelegate
Invocation list contains only one method

Multicast Delegates: Derived from System.MulticastDelegate
Invocation list may contain multiple methods

Multicast delegates contain two static methods to add and remove
references from invocation list: Combine and Remove

// assign to c the composition of delegates a and b
c = (MyDelegate2)Delegate.Combine(a, b);

// assign to d the result of removing a from c
d = (MyDelegate2)Delegate.Remove(c, a);  

// Iterate through c's invocation list
//  and invoke all delegates except a
Delegate[] DelegateList = c.GetInvocationList();
for (int i = 0; i < DelegateList.Length; i++) { 
         if (DelegateList[i].Target != aFoo1) { 
                ((MyDelegate2) DelegateList[i])(); 
        }
}

C# Delegates That Return Void Are Multicast Delegates In C#, Use the + and - Operators to Add and Remove
Invocation List Entries
Less verbose than Combine and Remove methods

MyDelegate a, b, c, d;
a = new MyDelegate(Foo);
b = new MyDelegate(Bar);
c = a + b;  // Compose two delegates to make another
d = c - a;  // Remove a from the composed delegate
a += b; // Add delegate b to a's invocation list
a -= b; // Remove delegate b from a's list

A Delegate Declaration Causes the Compiler to Generate a New Class

// delegate void MyDelegate3(string val);
class MyDelegate3 : System.MulticastDelegate  {
public MyDelegate3(object obj, methodref mref) 
                            : base (obj, mref) { //...
}
public void virtual Invoke(string val) { //... 
                        }
 };


Event : 实际上就是代理的一个实例

// MouseClicked delegate declared
public delegate void MouseClickedEventHandler();

public class Mouse
{
      // MouseClicked event declared 
        public static event MouseClickedEventHandler MouseClicked;
//...
}

Connecting to an Event

// Client’s method to handle the MouseClick event
private void MouseClicked() {
 //...
}
//.....

// Client code to connect to MouseClicked event
Mouse.MouseClicked += new MouseClickedEventHandler(MouseClicked);

// Client code to break connection to MouseClick event
Mouse.MouseClicked -= new MouseClickedEventHandler(MouseClicked);

Raising an Event

Check Whether Any Clients Have Connected to This Event 
    If the event field is null, there are no clients
Raise the Event by Invoking the Event’s Delegate

if (MouseClicked != null) 
    MouseClicked();

委托应用---异步回调
由于实例化委托是一个对象,所以可以将其作为参数进行传递,也可以将其赋值给属性。这样,方法便可以将一个委托作为参数来接受,并且以后可以调用该委托。这称为异步回调,是在较长的进程完成后用来通知调用方的常用方法。以这种方式使用委托时,使用委托的代码无需了解有关所用方法的实现方面的任何信息。

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

public void MethodWithCallback(int para1, int para2, Del callback)
{
    callback("The number is :"  + (para1 + para2).ToString());
}

MethodWithCallback(1, 2, handler);

Multicast Delegates(多波代理)

引用多个方法的委托,它连续调用每个方法,委托必须是同类型的,返回类型必须是void,不可以带输出参数(可以带引用参数)。多波代理应用于事件模型中

public class DelClass
{
    public void Method1(string message){}
    public void Method2(string message){}
}

DelClass obj = new DelClass();
Del d1 = obj.Method1;
Del d2 = obj.Method2; 
Del d3 = obj.DelegateMethod;

Del allMethodsDelegate = d1 + d2;
allMethodsDelegate += d3;

posted on 2007-09-19 00:07  执法长老  阅读(260)  评论(0编辑  收藏  举报

导航