@kuier1992
2015-11-05T20:13:09.000000Z
字数 1919
阅读 1680
C#
开头不知道怎么写了。直接就写吧。
事件
:定义了事件成员的类型允许类型或类型的实例 通知其他对象发生了特定的事情
。例如:Button类提供了Click事件,应用程序中的一个或多个对象可接收关于该事件的通知,以便在Button被单击后采取特定操作。(对于事件的说法还是很简单明了的。以前想说什么是事件总是说不出来)
定义了事件成员的类型能提供以下功能。
方法能登记它对事件的关注
方法能取消它对事件的关注
事件发生时,登记了的方法将受到通知
类型之所以能够提供事件通知功能,因为类型维护了一个已登记方法的列表。事件发生时,类型将通知列表中所有已登记的方法
事件引发时,引发事件的对象可能希望像接收事件通知的对象传递一些附加信息。这些信息需要封装到自己的类中,根据约定,这种类应该从System.EventArgs派生,而且类名以EventArgs结束。该类通常包含一组私有字段,以及一些用于公开这些字段的只读公共属性。
internal sealed class NewMailEventArgs : EventArgs {
private readonly String m_from, m_to, m_subject;
public NewMailEventArgs(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 event EventHandler<NewMailEventArgs> NewMail;
NewMail是事件名称,事件成员的类型是EventHandler,意味着“事件通知”的所有接收者多必须提供一个原型和EventHandler<NewMainEventArgs>
委托类型匹配的回调方法,所以方法原型必须具有以下形式
void MethodName(Object sender,NewMailEventArgs e);
按照约定,类要定义一个受保护的虚方法。引发事件时,类及其派生类中的代码会调用该方法。
代码大体如下
protected virtual void OnNewMail(NewMailEventArgs e) {
// Copy a reference to the delegate field now into a temporary field for thread safety
//e.Raise(this, ref m_NewMail);
//处于线程安全的考虑,现在将对委托字段的引用复制到一个临时变量中。
EventHandler<NewMailEventArgs> temp = Volatile.Read(ref NewMail);
// If any methods registered interest with our event, notify them
if (temp != null) temp(this, e);
}
类还必须有一个方法获取输入并转化为事件的引发。
public void SimulateNewMail(String from, String to, String subject) {
// Construct an object to hold the information we wish
// to pass to the receivers of our notification
NewMailEventArgs e = new NewMailEventArgs(from, to, subject);
// Call our virtual method notifying our object that the event
// occurred. If no type overrides this method, our object will
// notify all the objects that registered interest in the event
OnNewMail(e);
}