|
c#中的委托和事件的简单实例(1) 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[] args){ MyClass2 c2 = new MyClass2(); MyDelegate d = c2.createDelegate(); MyClass3 c3 = new MyClass3(); c3.callDelegate(d,"Calling the delegate"); } }
C#中的事件处理函数:
C#中的事件处理函数是一个具有特定参数形式的委托对象,其形式如下:
public delegate void MyEventHandler(object sender, MyEventArgs e);
其中第一个参数(sender)指明了触发该事件的对象,第二个参数(e)包含了在事件处理函数中可以被运用的一些数据。上面的MyEventArgs类是从EventArgs类继承过来的,后者是一些更广泛运用的类,如MouseEventArgs类、ListChangedEventArgs类等的基类。对于基于GUI的事件,你可以运用这些更广泛的、已经被定义好了的类的对象来完成处理;而对于那些基于非GUI的事件,你必须要从EventArgs类派生出自己的类,并将所要包含的数据传递给委托对象。下面是一个简单的例子:
public class MyEventArgs EventArgs{
|