浅析C#的事件处理和自定义事件[object sender , EventArgs e]
www.firnow.com 时间 : 2007-11-03 作者:佚名 编辑:本站 点击: [ 评论 ]
委托,改写客户端传递的参数。好了最终代码如下,好累
using System;
class MyEventArgs:EventArgs
{
private char keyChar;
public MyEventArgs(char keyChar)
{
this.keyChar=keyChar;
}
public char KeyChar
{
get
{
return keyChar;
}
}
}
class UserInputMonitor
{
public delegate void UserRequest(object sender,MyEventArgs e);
//定义委托
public event UserRequest OnUserRequest;
//此委托类型类型的事件
public void Run()
{
bool finished=false;
do
{
string inputString= Console.ReadLine();
if (inputString!="")
OnUserRequest(this,new MyEventArgs(inputString[0]));
}while(!finished);
}
}
public class Client
{
public static void Main()
{
UserInputMonitor monitor=new UserInputMonitor();
new Client(monitor);
monitor.Run();
}
private void ShowMessage(object sender,MyEventArgs e)
{
Console.WriteLine("捕捉到:{0}",e.KeyChar);
}
Client(UserInputMonitor m)
{
m.OnUserRequest+=new UserInputMonitor.UserRequest(this.ShowMessage);
//m.OnUserRequest+=new m.UserRequest(this.ShowMessage);
//注意这种写法是错误的,因为委托是静态的
}
}