5.2.4 correctly handle events that inherit controls in the base class
In the Kingtextbox event that is described in section 5.2.3.3, the functional statement defining the event is as follows:
/// <summary>
/// 获得本书更多内容,请看:
/// http://blog.csdn.net/ChengKing/archive/2008/08/18/2792440.aspx
/// </summary>
public virtual void RaisePostDataChangedEvent()
{
OnTextChanged(EventArgs.Empty);
}
protected virtual void OnTextChanged(EventArgs e)
{
if (TextChanged != null)
{
TextChanged(this, e);
}
}
The RaisePostDataChangedEvent method in the above code first invokes ontextchanged, and then ontextchanged actually invokes the TextChanged (This,e) event. It seems to be a bit of a ontextchanged, if you remove the method, the modified code looks like this:
public virtual void RaisePostDataChangedEvent()
{
if (TextChanged != null)
{
TextChanged(this, e);
}
}
Looks more concise, but this type of writing for controls that inherit this control, there are some limitations to handling events in the base class. Before you explain why, you need to talk about the topics in this section and how to handle the events that are inherited in the base class.
To handle inherited events, you need to override the protected OnEventName method inherited from the base class, instead of attaching a delegate, which does not guarantee that the default logic in the base class can be executed. In general, overridden methods should call the OnEventName method of the base class to ensure that delegates attached to the event are invoked (unless they are not invoked).
The above meaning is understood from a code perspective, and here is an example of the OnTextChanged method where the default event is invoked in the ontextchanged (the oneventname mentioned above) method:
protected virtual void OnTextChanged(EventArgs e)
{
if (TextChanged != null)
{
TextChanged(this, e);
}
}