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());
}
}
}
}
}
本博客内容,如需转载请务必保留超链接。Contact Me:Mail此处省略好几个字...