事件與代理是比較難理解的部分,本人從中學習中寫出的比較好理解的例子,C#中的delegate和C++中的函數指標基本是一回事,C#正是以delegate的形式實現了函數指標。不同的地方在於C#中delegate是型別安全的。
例一:
namespace DelegateTest
{
public delegate void MyDelegate();
class Test
{
static void Main(string[] args)
{
ChangedEvent chanevent = new ChangedEvent();
EventListener eventlis = new EventListener(chanevent);
chanevent.OnChanged();
Console.Read();
}
}
//定義一個包含事件成員的類,當發生變化時,就會觸發事件
public class ChangedEvent
{
public event MyDelegate Changed;
public void OnChanged()
{
if (Changed != null)
Console.WriteLine("觸發事件:");
Changed();
}
}
//建立包含處理方法的類
class EventListener
{
//用以儲存從構造涵數的參數傳遞來的對象,主要是為了以後解除事件綁定
// private ChangedEvent CE;
public EventListener(ChangedEvent ce)
{
// CE = ce;
ce.Changed += new MyDelegate(DispMethod);
}
private void DispMethod()
{
Console.WriteLine("This is called when the event fires.");
}
}
}
例二:
namespace Delegate2
{
public delegate void MyDelegate();
class Test
{
static void Main(string[] args)
{
ChangedEvent chanevent = new ChangedEvent();
A a=new A();
chanevent.Changed += new MyDelegate(a.DispMethod);
chanevent.OnChanged();
Console.Read();
}
}
class A
{
public void DispMethod()
{
Console.WriteLine("This is called when the event fires.");
}
}
//定義一個包含事件成員的類,當發生變化時,就會觸發事件
public class ChangedEvent
{
//public delegate void MyDelegate();
public event MyDelegate Changed;
public void OnChanged()
{
if (Changed != null)
{
Console.WriteLine("觸發事件:");
Changed();
}
}
例三:有參數形的Delegate
namespace ConsoleApplication1
{
//定義委託
public delegate bool CompareInt(int a, int b);
public class MyCompare
{
public static bool ShowResult(int x , int y)
{
bool index = x > y ? true : false;
return index;
}
}
class Program
{
static void Main(string[] args)
{
CompareInt myDelegate = new CompareInt(MyCompare.ShowResult);
int a = 20;
int b = 15;
bool whoBigger = myDelegate(a, b);
Console.WriteLine(" a > b ?: " + whoBigger );
Console.Read();
}
}
}