在.NET 1.1中处理事件时很麻烦的事情。比如创建下面这个类:
[Serializable]
public class LogEntry
{
private string iD;
/// <summary>
/// 事件ID
/// </summary>
public string ID
{
get { return iD; }
set { iD = value; }
}
string message;
/// <summary>
/// 事件内容
/// </summary>
public string Message
{
get { return message; }
set { message = value; }
}
}
等你需要把LogEntry当成参数传递时,就需要创建两个新的类型LogEntryArgs和LogEntryEventHandler.分别定义如下:
public class LogEntryArgs:EventArgs
{
private LogEntry entry;
public LogEntryArgs(LogEntry entry)
{
this.entry = entry;
}
public LogEntry Entry
{
get { return entry;}
}
}
public delegate void LogEntryEventHandler(object sender, LogEntryArgs e);
如果系统中参数比较多,这种重复劳动工作量就很多,导致系统的类型增加。我们可以使用.NET 2.0 中的泛型克服这个问题。
1. 首先为参数定义一个公用的泛型类型:
public class TEventArgs<T>:EventArgs
{
public TEventArgs(T param)
{
this.param = param;
}
T param;
public T Param
{
get { return param; }
}
}
2. 然后就可以使用框架自带的EventHandler<>类创建事件:
public event EventHandler<TEventArgs<LogEntry>> LogWritten;
3.使用的方法如下:
EventHandler<TEventArgs<LogEntry>> temp = LogWritten;
if (temp != null)
{
temp(this, new TEventArgs<LogEntry>(entry));
}
##例子的完整代码如下:
public class LogManagerImp
{
public void Write(LogEntry entry)
{
EventHandler<TEventArgs<LogEntry>> temp = LogWritten;
if (temp != null)
{
temp(this, new TEventArgs<LogEntry>(entry));
}
}
public event EventHandler<TEventArgs<LogEntry>> LogWritten;
#endregion
}