异步回调:实例化委托是一个对象,故可将其作为参数进行传递,也可将其赋值给属性。这样,方法便可将一个委托作为参数来接受,并在以后可以调用该委托。
多播委托:举个例子,del是一个委托,Method1和Method2是obj对象的两个方法,则委托可这样写:
del d1=obj.Method1;
del d2=obj.Method2;
del d3=d1+d2;
d3( );
当然Method1和Method2可不属于同一实例,但两个方法都必须不能有返回值。
异步回调和多播的一个例子:
class
Program
... {
public delegate void del(string msg);
static void Main(string[] args)
...{
DelClass myDel=new DelClass();
del handle = new del(myDel.printMsg);
handle("hello world");
DelHandle myHandle = new DelHandle();
handle = new del(myHandle.hangleMsg);
handle("handle msg");
//异步回调
printAllMsg("call", "back", handle);
//多播
del d1 = myDel.method1;
del d2 = myDel.method2;
del d3 = myDel.printMsg;
del allMethod = d1 + d2;
allMethod += d3;
allMethod("all method ");
Console.ReadLine();
}
private static void printAllMsg(string param1, string param2, del myCallBack)
...{
myCallBack(param1 + param2);
}
}
public class DelClass
... {
public void printMsg(string msg)
...{
Console.WriteLine(msg);
}
public void method1(string msg)
...{
Console.WriteLine(msg+"method1");
}
public void method2(string msg)
...{
Console.WriteLine(msg + "method2");
}
}
public class DelHandle
... {
public void hangleMsg(string msg)
...{
Console.WriteLine(msg);
}
}
... {
public delegate void del(string msg);
static void Main(string[] args)
...{
DelClass myDel=new DelClass();
del handle = new del(myDel.printMsg);
handle("hello world");
DelHandle myHandle = new DelHandle();
handle = new del(myHandle.hangleMsg);
handle("handle msg");
//异步回调
printAllMsg("call", "back", handle);
//多播
del d1 = myDel.method1;
del d2 = myDel.method2;
del d3 = myDel.printMsg;
del allMethod = d1 + d2;
allMethod += d3;
allMethod("all method ");
Console.ReadLine();
}
private static void printAllMsg(string param1, string param2, del myCallBack)
...{
myCallBack(param1 + param2);
}
}
public class DelClass
... {
public void printMsg(string msg)
...{
Console.WriteLine(msg);
}
public void method1(string msg)
...{
Console.WriteLine(msg+"method1");
}
public void method2(string msg)
...{
Console.WriteLine(msg + "method2");
}
}
public class DelHandle
... {
public void hangleMsg(string msg)
...{
Console.WriteLine(msg);
}
}