111,123
社区成员
发帖
与我相关
我的任务
分享using System;
namespace SomethingsBase
{
/// <summary>
/// 接口
/// </summary>
public interface ISomething
{
event EventHandler<ReportStatuEventArgs> ReportStatuEvent;
void DoSoething();
void OnDoSomething(ReportStatuEventArgs rsea);
}
/// <summary>
/// 自定义的事件参数
/// </summary>
public class ReportStatuEventArgs : EventArgs
{
public ReportStatuEventArgs(string s)
{
msg = s;
}
private string msg;
public string Message
{
get { return msg; }
}
private DateTime startTime = DateTime.Now;
public DateTime StartTime
{
get { return startTime; }
}
}
}using System;
using System.Collections.Generic;
using System.Text;
using SomethingsBase;
namespace DoSomethings
{
public class DoSomething:ISomething
{
#region ISomething 成员
public event EventHandler<ReportStatuEventArgs> ReportStatuEvent;
public void DoSoething()
{
//...
//某种情况下引发事件
ReportStatuEventArgs e = new ReportStatuEventArgs("做某件事");
OnDoSomething(e);
//...
}
public void OnDoSomething(ReportStatuEventArgs rsea)
{
EventHandler<ReportStatuEventArgs> handler = ReportStatuEvent;
if (handler != null)
{
handler(this, rsea);
}
}
#endregion
}
}using System;
using SomethingsBase;
namespace EventTest
{
class Program
{
static void Main(string[] args)
{
//这里可以用反射加载对象,示例为了简单就直接new出来了
ISomething some = new DoSomethings.DoSomething();
//指定事件方法
some.ReportStatuEvent+=new EventHandler<ReportStatuEventArgs>(some_ReportStatuEvent);
for (int i = 0; i < 20; i++)
{
some.DoSoething();
System.Threading.Thread.Sleep(500);
}
Console.ReadKey();
}
static void some_ReportStatuEvent(object sender, ReportStatuEventArgs e)
{
Console.WriteLine(e.Message +" 在 " + e.StartTime.ToString("HH:mm:ss"));
}
}
}