高级编程里的一个例子,我见很好啊。
using System;
using System.Collections;
using System.Windows.Forms;namespace Event
{
enum RequestType
{
AdRequest,
PersonMessageRequest
};
//事件处理类UserRequestEventArgs,没必要继承EventArgs,
//EventArgs又没有提供虚函数(也没必要提供)
class UserRequestEventArgs
{
private RequestType request;
public UserRequestEventArgs(RequestType request)
{
this.request=request;
}
public RequestType Request
{
get
{
return request;
}
}
}
class UserInputMonitor
{
//事件委托
public delegate void UserRequest(object sender,UserRequestEventArgs e);
//Event关键字说明这个委托是个事件
public event UserRequest OnUserRequest;public UserInputMonitor()
{
//绑定事件处理方法
OnUserRequest += new Event.UserInputMonitor.UserRequest(monitor_OnUserRequest);
}public void Run()
{
Console.WriteLine(\"Input:\");
while(true)
{
//输入A则显示AdRequest,输入P则显示PersonMessageRequest
string response = Console.ReadLine();
char responseChar = (response==\"\")?' ':char.ToUpper(response[0]);
switch(responseChar)
{
case 'A':
this.OnUserRequest(this,new UserRequestEventArgs(RequestType.AdRequest));
break;
case 'P':
this.OnUserRequest(this,new UserRequestEventArgs(RequestType.PersonMessageRequest));
break;
case 'X':
return;
}
}
}//事件处理方法
protected void monitor_OnUserRequest(object sender,UserRequestEventArgs e)
{
//根据枚举值决定显示的信息
switch(e.Request)
{
case RequestType.AdRequest:
MessageBox.Show(\"It's AdRequest!\");
break;
case RequestType.PersonMessageRequest:
MessageBox.Show(\"It's PersonMessageRequest!\");
break;
}
}
}
class AppMain
{
public AppMain()
{}static void Main()
{
UserInputMonitor user = new UserInputMonitor();
user.Run();
Console.ReadLine();
}
}
}