委托——15分钟快速入门教程






3.13/5 (26投票s)
2003年8月10日
1分钟阅读

89537

1246
通过示例程序教授委托。
特点
- 委托调用带参数的实例方法。
- 委托调用带参数的静态方法。
- 委托多播:委托一次调用多个方法。
说明
只需编译并运行示例。代码已注释,易于理解。
概念/背景
委托只是将调用重新路由到其引用的函数/方法的简单机制。这个想法很简单。调用委托会调用委托引用的方法/函数。问题是,为什么使用委托?为什么不直接调用函数/方法呢?
- 委托与委托引用的方法之间的关联是在运行时建立的 - 因此,您获得了灵活性。
- 多播:即将几个方法/函数关联到单个委托。调用一个委托会立即触发该委托引用的所有方法。
代码片段
这是您的委托
- 委托 - 请注意,委托具有与其引用的所有函数/方法相同的签名。
- 一个委托可以引用多个函数/方法 - 这称为多播。
public delegate int SomeDelegate(int nID, string sName);
委托引用的方法可以在 WorkerClass 中找到
public class WorkerClass
{
//(1) First method (instance method) referenced by delegate:
public int InstanceMethod(int nID, string sName) {...}
//(2) Second method (static method) referenced by delegate:
static public int StaticMethod(int nID, string sName) {...}
};
这两个方法的唯一区别在于“InstanceMethod”是一个实例方法,也就是说,它必须由 WorkerClass 的实际实例调用。StaticMethod 是一个静态成员函数 - 通过以下方式调用它:WorkerClass.StaticMethod(10,"aaa");
函数的作用是什么?
- 它会将“nID”乘以“sName”的长度。例如,nID=10,sName="aaa"(长度=3)。因此返回值=10x3=30。
- 它将写入控制台
"InstanceMethod invoked, return value=..." OR "StaticMethod invoked, return value=..."
委托与其引用的方法之间的关联可以在 main(...) 中找到。
//PART 1: invoking instance method
WorkerClass wr = new WorkerClass();
SomeDelegate d1 = new SomeDelegate(wr.InstanceMethod);
//Associating delegate with wr.InstanceMethod
Console.WriteLine("Invoking delegate InstanceMethod, return={0}",
d1(5, "aaa") ); //Invoking wr.InstanceMethod with input parameters.
//PART 2: invoking static method
SomeDelegate d2 = new SomeDelegate(WorkerClass.StaticMethod);
//Associating delegate with WorkerClass.StaticMethod (NOTE: "wr"
//instance is NOT used. The class itself is used!!)
Console.WriteLine("Invoking delegate StaticMethod, return={0}",
d2(5, "aaa") ); //Invoking InstanceMethod with input parameters.
//PART 3: MultiCAST!
Console.WriteLine();
Console.WriteLine("Testing delegate multi-cast..");
SomeDelegate d3 = (SomeDelegate) Delegate.Combine(d1, d2);
Console.WriteLine("Invoking delegate(s) d1 AND d2 (multi-cast), return={0} ",
d3(5, "aaa") ); //Fire BOTH delegates (d1 AND d2) by firing d3!
结论
就是这样。很简单,对吧?