2016-04-03 34 views
0

我對多個元素使用了void。如按鈕,標籤,pictureboxes ....獲取發件人的元素類型(Button,PictureBox等..)

但我需要修改一些發件人的變量。如姓名,上,左等......這是我的代碼:

private void FareSurukle(object sender, MouseEventArgs e) 
{ 
    MessageBox.Show(((TYPE_COMES_HERE)sender).Name);  
} 

如果我編輯「TYPE_COMES_HERE」,以圖片框,它適用於圖片框。但它會給其他元素帶來錯誤。像按鈕一樣。

是否可以在不聲明其類型的情況下獲取並修改發件人的變量?或者,我可以使用if進行發件人類型檢查嗎?

回答

4

我需要修改一些發件人的屬性,如姓名,頂部,左

您不必檢查確切的類型。您提到的控件都從包含所有這些屬性的基類繼承而來,適當地命名爲Control

MessageBox.Show(((Control)sender).Name); 
+0

謝謝!它和我想要的完全一樣。我也想過這個,但我不知道他們被稱爲「控制」。我試過其他的東西,比如「Type,Element」... – Eren

+0

你可以[在MSDN上檢查繼承樹](https://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox( v = vs.110)的.aspx)。 – CodeCaster

2

您可以嘗試鑄造每種類型,如果沒有null用它做什麼:

var button = sender as Button; 
if (button != null) 
{ 
    // do something with button 
} 
var pictureBox = sender as PictureBox; 
if (pictureBox != null) 
{ 
    // do something with pictureBox 
} 
0
private void FareSurukle(object sender, MouseEventArgs e) 
{ 
    if (sender is PictureBox) 
    { 
     // do something 
    } 
    else if (sender is Label) 
    { 
     // do something 
    } 
    else if (sender is Button) 
    { 
     // do something 
    } 
}