如有不明白的地方欢迎加QQ群14670545 探讨
最近在看委托,然后看到事件,以前一直很模糊,关于事件的触发者和响应者的关联。贴一个简单的例子:
1.新建一个类Control.cs
using System;
namespace EventComplex
{
/*
* C#中的事件处理实际上是一种具有特殊签名的delegate
*/
public class Control
{
/// <summary>
/// 代表事件发送者
/// </summary>
/// <param name="sender">代表事件发送者</param>
/// <param name="e">事件参数类
/// <remarks>用来包含与事件相关的数据,所有的事件参数类都必须从System.EventArgs类派生</remarks>
/// </param>
public delegate void MyEventHandler(object sender, MyEventArgs e);//System.EventArgs e
public event MyEventHandler MyEvent;
public Control()
{
this.MyEvent += new MyEventHandler(RaiseSomeEvent);
}
/// <summary>
/// 一个事件
/// </summary>
public void RaiseSomeEvent(object sender, MyEventArgs e)
{
Console.WriteLine("hello " + e.ParamName);
Console.ReadLine();
}
public void RiseSomeEvent()
{
//System.EventArgs e = new System.EventArgs();
Console.Write("Please input 'Name':");
string _param = Console.ReadLine();//ReadLine:按下回车以后才读取,然后触发MyEvent事件
//if (_param.Equals("jon"))//在用户输入jon的情况下触发事件,否则不触发
MyEvent(this, new MyEventArgs(_param));//MyEvent(this,e)
}
}
public class MyEventArgs : System.EventArgs
{
public string ParamName;
public MyEventArgs(string _name)
{
ParamName = _name;
}
}
}
2.我们去Main函数里面测试一下;
public static void demo4()
{
Control ctr = new Control();
ctr.MyEvent += new Control.MyEventHandler(ResponseSomeEvent);
ctr.RiseSomeEvent();
}
public static void ResponseSomeEvent(object sender, EventArgs e)
{
Console.WriteLine("Some event occur!");
}
static void Main(string[] args)
{
demo4();
}
//===============================================分割线================================================
namespace EventTest
{
class Program
{
static void Main(string[] args)
{
ReadBook read = new ReadBook();
read.MyEvent += ResponseSomeEvent;
read.RiseSomeEvent();
}
public static void ResponseSomeEvent(object sender, SampleEventArgs e)
{
Console.WriteLine(e.name+" read the book!");
Console.ReadLine();
}
}
public class ReadBook
{
public event EventHandler<SampleEventArgs> MyEvent;
public ReadBook()
{
}
public void RiseSomeEvent()
{
Console.Write("Please input 'Name':");
string _param = Console.ReadLine();
if (this.MyEvent != null)
MyEvent(this, new SampleEventArgs(_param));
}
}
public class SampleEventArgs : System.EventArgs
{
public SampleEventArgs(string s)
: base()
{
this.name = s;
}
public string name
{
get;
private set;
}
}
}