C#中简单自行产生事件并处理实例
using System;
namespace DeleAndEvent
{
/// <summary>
/// 一个产生自定义事件并自行处理的程序
/// </summary>
class Demo
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Dele dele=new Dele();
dele.MyEvent+=new DeleAndEvent.Dele.MyEventHandler(dele.ProccessMyEvent);
dele.RaiseEvent();
Console.Read();
}
}
class Dele
{
/// <summary>
/// 声明代理
/// </summary>
public delegate void MyEventHandler(object sender,MyEventArgs e);
/// <summary>
/// 声明事件
/// </summary>
public event MyEventHandler MyEvent;
/// <summary>
/// 产生事件
/// </summary>
public void RaiseEvent()
{
if(MyEvent!=null)
{
MyEvent(this,new MyEventArgs());//这里是产生事件的代码
}
}
/// <summary>
/// 处理处理方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void ProccessMyEvent(object sender,MyEventArgs e)
{
Console.WriteLine("事件来源:{0},发生时间:{1}",sender.ToString(),e.RaiseTime);
}
}
/// <summary>
/// 自定义了一个事件类
/// </summary>
class MyEventArgs:EventArgs
{
private DateTime raiseTime;
public MyEventArgs()
{
this.raiseTime=System.DateTime.Now;
}
public DateTime RaiseTime
{
get
{
return this.raiseTime;
}
}
}
}
namespace DeleAndEvent
{
/// <summary>
/// 一个产生自定义事件并自行处理的程序
/// </summary>
class Demo
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Dele dele=new Dele();
dele.MyEvent+=new DeleAndEvent.Dele.MyEventHandler(dele.ProccessMyEvent);
dele.RaiseEvent();
Console.Read();
}
}
class Dele
{
/// <summary>
/// 声明代理
/// </summary>
public delegate void MyEventHandler(object sender,MyEventArgs e);
/// <summary>
/// 声明事件
/// </summary>
public event MyEventHandler MyEvent;
/// <summary>
/// 产生事件
/// </summary>
public void RaiseEvent()
{
if(MyEvent!=null)
{
MyEvent(this,new MyEventArgs());//这里是产生事件的代码
}
}
/// <summary>
/// 处理处理方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void ProccessMyEvent(object sender,MyEventArgs e)
{
Console.WriteLine("事件来源:{0},发生时间:{1}",sender.ToString(),e.RaiseTime);
}
}
/// <summary>
/// 自定义了一个事件类
/// </summary>
class MyEventArgs:EventArgs
{
private DateTime raiseTime;
public MyEventArgs()
{
this.raiseTime=System.DateTime.Now;
}
public DateTime RaiseTime
{
get
{
return this.raiseTime;
}
}
}
}
说明:
1.系统提供的System.EventHandler其实也是一个delegate,如public delegate void EventHandler(Object sender, EventArgs e);
2.事件声明格式:event [事件处理的delegate] [事件名],如在本例中声明事件处理delegate和事件的代码,
public delegate void MyEventHandler(object sender,MyEventArgs e);
public event MyEventHandler MyEvent;
声明了事件处理委托MyEventHandler和事件MyEvent。
3.产生事件代码:
MyEvent(this,new MyEventArgs());
注意这里与MyEventHandler的参数一一对应。
4.添加事件处理:
dele.MyEvent+=new DeleAndEvent.Dele.MyEventHandler(dele.ProccessMyEvent);