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);
}
}