纸上得来终觉浅,绝知此事要躬行。

 

c# 事件学习

以下是带事件数据的事件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConApp_2_Event
{
class Program
{
static void Main(string[] args)
{
RequestKey rk
= new RequestKey();
rk.OnReqKey
+= new RequestKey.ReqKey(rk_OnReqKey);
rk.Run();
}
static void rk_OnReqKey(object sender, RequestKeyEventArgs rkea)
{
Console.WriteLine(
"您输入了<{0}>", rkea.InputText);
}
}
public class RequestKeyEventArgs : EventArgs
{
public string InputText { get; set; }
}
public class RequestKey
{
public delegate void ReqKey(object sender, RequestKeyEventArgs rkea);
public event ReqKey OnReqKey;
public void Run()
{
while (true)
{
string a = Console.ReadLine();
RequestKeyEventArgs re
= new RequestKeyEventArgs();
re.InputText
= a;
OnReqKey(
this, re);
}
}
}
}

上面的多了一个RequestKeyEventArgs类,此类继承了EventArgs类,就是通过这个类传递了事件中的数据
下面是不带事件数据的事件:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConApp_1_Event
{
class Program
{
static void Main(string[] args)
{
Program pro
= new Program();
SJR _sjr
= new SJR();
_sjr.OnRequest
+= new SJR.UsersRequest(pro.Pro_OnRequest);
_sjr.Run();
}
private void Pro_OnRequest(object sender, EventArgs e)
{
Console.WriteLine(
"OnRequest事件触发了");
}
}
public class SJR
{
public delegate void UsersRequest(object sender, EventArgs e);
public event UsersRequest OnRequest;
public void Run()
{
while (true)
{
if (Console.ReadLine() == "s")
{
OnRequest(
this, new EventArgs());
}
}
}
}
}

 

posted on 2011-01-17 10:10  JRoger  阅读(6312)  评论(0编辑  收藏  举报

导航