简体   繁体   中英

extending control - use sender or this

I am extending a control's capabilities. I want to know if there are any advantages in using a casted sender vs this keyword in an event. For example:

public class CustomTextBox : TextBox
{
    public CustomTextBox()
    {
        Loaded += CustomTextBox_Loaded;
    }
    void CustomTextBox_Loaded(object sender, RoutedEventArgs e)
    {
        //use either
        var c = (CustomTextBox)sender;
        //or
        var c2 = this;
        //do whatever...
    }
}

I believe using this might be more efficient (No casting necessary).

usually events are handled outside the class which publishes them, in the subscriber class. In such a setup, it may be desired to get the reference of publisher in subscriber & that is when type casting the sender to get the reference of publisher comes handy.

I agree, in my opinion, if you can get the reference of publisher without type casting thats better, you should use this .

But since you are extending a control, please check if its really necessary to use event of the base class. An event is for the outside world, and not for child classes.

If the event pattern has been implemented correctly in the base control class, I would expect a virtual method responsible for raising which you can override while extending the control, like this -

class CustomTextBox  : TextBox
{      

   protected override void OnClick(EventArgs e)
   {          
       //place your code here if you want to do the processing before the contol raises the event. Before call to  base.OnClick(e);
       base.OnClick(e); // call to base funciton fires event 
       //place your code here if you want to do the processing after the contol raises the event. After call to  base.OnClick(e);
   }

}

Hope it helps.

I doubt you would find any measurable performance difference either way, especially for an event like Loaded that is only going to be raised once during the lifetime of the control.

That said, it seems to me you should go ahead and use this , just because it's more convenient and expressive. If your method is already in the code of the class of the sender, why not? What possible gain could there be in code comprehension, ease of authoring, maintainability, or any other common goal in programming to using the sender parameter instead of just using this ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM