1.设计事件要公开事件类型:
第一步:定义类型来容纳所有需要发送给事件通知接收者的附加信息
public class NewMaillEventArgs:EventArgs
{
private readonly string _m_from;
private readonly string _m_to;
private readonly string _m_subject;
public NewMaillEventArgs(string from,string to,string subject)
{
_m_from = from;
_m_to = to;
_m_subject = subject;
}
public string From { get { return _m_from; } }
public string To { get { return _m_to; } }
public string Subject { get { return _m_subject; } }
}
第二步:定义事件成员
事件成员使用C#关键字event来定义。每个事件成员都要指定以下内容:
一个可访问性标识符(几乎肯定是Public,这样其他代码才能访问该事件成员);
另一个委托类型,它指出要调用的方法的原型,以及一个名称(可以是任意有效的标识符)。
//定义成员变量
public event EventHandler<NewMaillEventArgs> NewMaill;
注意:事件模式要求所有事件处理程序(方法)的返回类型都是void;
第三步:定义负责引发事件的方法来通知事件的登记对象。
//如果类是密封的,该方法要声明为私有和非虚
protected virtual void OnNewMaill(NewMaillEventArgs e)
{
//出于线程安全的考虑,现在将对委托字段的引用复制到一个临时变量时
EventHandler<NewMaillEventArgs> temp = Volatile.Read(ref NewMaill);
//任何方法登记了事件的关注,就通知它们
if (temp!=null)
{
temp(this, e);
}
}
第四步:定义方法将输入转化为期望事件
public void SimulateNewMaill(String from, String to, String subject)
{
NewMaillEventArgs e=new NewMaillEventArgs(from,to,subject);
OnNewMaill(e);
}