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);
using System; file://步骤1:声明委托对象 public delegate void MyHandler1(object sender,MyEventArgs e); public delegate void MyHandler2(object sender,MyEventArgs e);
file://步骤2:创建事件处理函数的方法 class A{ public const string m_id="Class A"; public void OnHandler1(object sender,MyEventArgs e){ Console.WriteLine("I am in OnHandler1 and MyEventArgs is {0}", e.m_id); } public void OnHandler2(object sender,MyEventArgs e){ Console.WriteLine("I am in OnHandler2 and MyEventArgs is {0}", e.m_id); }
file://步骤4:通过委托对象(也就是触发事件)来调用被包含的方法 class B{ public event MyHandler1 Event1; public event MyHandler2 Event2; public void FireEvent1(MyEventArgs e){ if(Event1 != null){ Event1(this,e); } } public void FireEvent2(MyEventArgs e){ if(Event2 != null){ Event2(this,e); } } } public class MyEventArgs EventArgs{ public string m_id; } public class Driver{ public static void Main(){ B b= new B(); A a= new A(b); MyEventArgs e1=new MyEventArgs(); MyEventArgs e2=new MyEventArgs(); e1.m_id ="Event args for event 1"; e2.m_id ="Event args for event 2"; b.FireEvent1(e1); b.FireEvent2(e2); } }