如果你看了本BLOG寫的委託的文章,理解本文應該比較容易,C#中的事件的實現是通過委託直接實現的,所以本文只給出事件實現的程式碼範例,如果你明白了委託,相信看懂本代碼應該不難。
using System;
namespace Events
{
delegate void SomeDelegate(string sender);
interface ISomeInterface
{
event SomeDelegate SomeEvent;
void PerformSomeEvent();
void SomeEventHandler(string sender);
}
abstract class AbstractClass:ISomeInterface
{
public virtual event SomeDelegate SomeEvent;
public abstract void SomeEventHandler(string sender);
public abstract void PerformSomeEvent();
protected void PerformSomeEventInternal(string sender)
{
if(null!=SomeEvent)
{
SomeEvent(sender);
}
}
protected void SomeEventHandlerInternal(string sender,string receiver)
{
Console.WriteLine("some event has been handler");
Console.WriteLine(" Sender is ["+ sender+"]");
Console.WriteLine("Receiver is ["+receiver+"]");
Console.WriteLine("------------------------------------");
}
}
class SomeClass:AbstractClass,ISomeInterface
{
public override void PerformSomeEvent()
{
PerformSomeEventInternal("Some Class");
}
public override void SomeEventHandler(string sender)
{
SomeEventHandlerInternal(sender,"Some Class");
}
}
class AnotherClass:AbstractClass,ISomeInterface
{
public override void PerformSomeEvent()
{
PerformSomeEventInternal("Another Class");
}
public override void SomeEventHandler(string sender)
{
SomeEventHandlerInternal(sender,"Another Class");
}
}
class SomeApplication
{
public static void SomeEventStaticHander(string sender)
{
Console.WriteLine("some event has been handler.");
Console.WriteLine(" Sender is ["+ sender+"]");
Console.WriteLine("Receiver is [some application]");
Console.WriteLine("-------------------------------------");
}
static void Main(string [] args)
{
SomeClass someclass=new SomeClass();
AnotherClass anotherclass=new AnotherClass();
someclass.SomeEvent+=new SomeDelegate(someclass.SomeEventHandler);
someclass.SomeEvent+=new SomeDelegate(anotherclass.SomeEventHandler);
someclass.SomeEvent+=new SomeDelegate(SomeApplication.SomeEventStaticHander);
someclass.PerformSomeEvent();
Console.ReadLine();
}
}
}
啟動並執行結果: