Sunding asp.net3.5 Control and Component development technology series-events and data postback mechanism (ii)

Source: Internet
Author: User

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);
   }
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.