|
C#中的委托:
委托,顾名思义,就是中间代理人的意思。C#中的委托允许你将一个对象中的方法传递给另一个能调用该方法的类的某个对象。你可以将类A中的一个方法m(被包含在某个委托中了)传递给一个类B,这样类B就能调用类A中的方法m了。同时,你还可以以静态(static)的方式或是实例(instance)的方式来传递该方法。所以这个概念和C++中的以函数指针为参数形式调用其他类中的方法的概念是十分类似的。
委托的概念首先是在Visual J++中被提出来的,现在C#也应用了委托的概念,这也可谓是"拿来主义"吧。C#中的委托是通过继承System.Delegate中的一个类来实现的,下面是具体的步骤:
1. 声明一个委托对象,其参数形式一定要和你想要包含的方法的参数形式一致。
2. 定义所有你要定义的方法,其参数形式和第一步中声明的委托对象的参数形式必须相同。
3. 创建委托对象并将所希望的方法包含在该委托对象中。
4. 通过委托对象调用包含在其中的各个方法。
以下的C#代码显示了如何运用以上的四个步骤来实现委托机制的:
using System; file://步骤1: 声明一个委托对象 public delegate void MyDelegate(string input);
file://步骤2::定义各个方法,其参数形式和步骤1中声明的委托对象的必须相同 class MyClass1{ public void delegateMethod1(string input){ Console.WriteLine( "This is delegateMethod1 and the input to the method is {0}", input); } public void delegateMethod2(string input){ Console.WriteLine( "This is delegateMethod2 and the input to the method is {0}", input); } }
file://步骤3:创建一个委托对象并将上面的方法包含其中 class MyClass2{ public MyDelegate createDelegate(){ MyClass1 c2=new MyClass1(); MyDelegate d1 = new MyDelegate(c2.delegateMethod1); MyDelegate d2 = new MyDelegate(c2.delegateMethod2); MyDelegate d3 = d1 + d2; return d3; } }
file://步骤4:通过委托对象调用包含在其中的方法 class MyClass3{ public void callDelegate(MyDelegate d,string input){ d(input); } } class Driver{ static void Main(string[] ar [1] [2] [3] 下一页
|