2015-11-15 31 views
0

我伸出的控制的能力。我想知道在使用鑄造發件人方面是否有任何優勢vs 關鍵字在事件中。例如:延伸的控制 - 使用發件人或這個

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

我相信使用可能更有效(無鑄造必要)。

回答

1

通常事件被該公司出版它們,在用戶類的類之外的處理。在這樣的設置中,可能希望獲得發行者的參考,該發行者是在發送者的類型轉換以獲得發行者的引用時用戶&來的方便。

我同意,在我看來,如果你能更好地得到出版商的無型鑄造這就是引用,你應該使用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); 
    } 

} 

希望它能幫助。

0

我懷疑你會發現任何可衡量的性能差異,特別是對於像Loaded這樣的事件,只會在控件的整個生命週期中提升一次。

這就是說,在我看來,你應該繼續使用this,只是因爲它的方便和表現力。如果你的方法已經在發件人類的代碼中,爲什麼不呢?莫不是在理解代碼,便於製作,維護,或編程使用sender參數,而不是僅僅使用this任何其他共同的目標是什麼可能收穫?