事件与委托
代码段创建类的对象并在该对象上调用方法,此情况下,调用程序是主动,而对象是被动的;但是也有相反的情况,如对象执行过程中发生某些事情通知调用程序,此类事情称之为事件(Event),z其他代码段编写一种方法接收和处理发布的事件,此过程称之为委托(delegate)。
需要注意的是事件类型与委托标识符要匹配
using System;
/*
public delegate void EvenNumberHandler(int Number);//定义了一个委托
class Counter
{
public event EvenNumberHandler OnEvenNumber;
public Counter()
{
OnEvenNumber = null;
}
public void CountTo100()
{
int CurrentNumber;
for (CurrentNumber = 0; CurrentNumber <= 100; CurrentNumber++)
{
if (CurrentNumber % 2 == 0)
if (OnEvenNumber != null)
{
OnEvenNumber(CurrentNumber);
}
}
}
}
class EvenNumberHandlerClass
{
public void EvenNumberFound(int EvenNumber)
{
Console.WriteLine(EvenNumber);
}
}
class EvenNumberHandlerClass2
{
public void EvenNumberFound2(int EvenNumber1)
{
Console.WriteLine(EvenNumber1);
}
}
class MainClass
{
public static void Main()
{
Counter MyCounter = new Counter();
EvenNumberHandlerClass MyEvenNumberHandlerClass = new EvenNumberHandlerClass();
EvenNumberHandlerClass2 MyEvenNumberHandlerClass2 = new EvenNumberHandlerClass2();
MyCounter.OnEvenNumber += new EvenNumberHandler(MyEvenNumberHandlerClass.EvenNumberFound);//可以将任意多的委托
MyCounter.OnEvenNumber += new EvenNumberHandler(MyEvenNumberHandlerClass2.EvenNumberFound2); //安装事件,事件在前 委托在后 //实例与一个事件联系起来
MyCounter.CountTo100();
}
}
*/
//标准化事件的设计
public delegate void EvenNumberHandler (object Originator,OnEvenNumberEventArgs EvenNumberEventArgs);
class Counter
{
public event EvenNumberHandler OnEvenNumber;
public Counter()
{
OnEvenNumber = null;
}
public void CountTo100()
{
int CurrentNumber;
for (CurrentNumber = 0; CurrentNumber <= 100; CurrentNumber++)
{
if (CurrentNumber % 2 == 0)
{
if (OnEvenNumber != null)
{
OnEvenNumberEventArgs EventArguments;
EventArguments = new OnEvenNumberEventArgs(CurrentNumber);
OnEvenNumber(this, EventArguments);//????存在疑问this到底是如何使用的
}
}
}
}
}
public class OnEvenNumberEventArgs : EventArgs
{
private int EvenNumber;
public OnEvenNumberEventArgs(int EvenNumber)
{
this.EvenNumber = EvenNumber;//this
}
public int Number
{
get
{
return EvenNumber;
}
}
}
class EventNumberHandlerClass
{
public void EvenNumberFound(object Originator, OnEvenNumberEventArgs EvenNumberEventArgs)
{
Console.WriteLine(EvenNumberEventArgs.Number);
}
}
class MainClass
{
public static void Main()
{
Counter MyCounter = new Counter ();
EventNumberHandlerClass MyEventNumberHandlerClass = new EventNumberHandlerClass();
MyCounter.OnEvenNumber += new EvenNumberHandler(MyEventNumberHandlerClass.EvenNumberFound);
MyCounter.CountTo100();
}
}