扩展控制 - 使用 sender 或 this

extending control - use sender or this

我正在扩展控件的功能。我想知道在事件中使用 casted sender 与 this 关键字是否有任何优势。例如:

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...
    }
}

我相信使用 this 可能更有效(无需转换)。

我怀疑您是否会发现任何可衡量的性能差异,尤其是对于像 Loaded 这样的事件,它只会在控件的生命周期内引发一次。

也就是说,在我看来您应该继续使用 this,只是因为它更方便且更易于表达。如果你的方法已经在发件人的 class 的代码中,为什么不呢?使用 sender 参数而不是仅使用 this 在代码理解、易于编写、可维护性或任何其他编程的共同目标方面可能有什么好处?

通常事件是在发布它们的 class 之外,在订阅者 class 中处理的。在这样的设置中,可能需要在订阅者中获取发布者的引用,这时类型转换发送者以获取发布者的引用就派上用场了。

我同意,在我看来,如果您可以在不进行类型转换的情况下获得发布者的引用,那就更好了,您应该使用 this

但是由于您是扩展控件,请检查是否真的有必要使用基础事件class。事件是针对外部世界的,而不是针对 child classes 的。

如果事件模式已在基本控件中正确实现 class,我希望有一个虚拟方法负责引发,您可以在扩展控件时覆盖它,就像这样 -

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

}

希望对您有所帮助。