2009-02-09 52 views

回答

129

這是一種方式:

if (!(sender is TextBox)) {...} 
+3

對於這種特殊的情況下,我寧願如果(發件人是TextBox == false)。像這樣的笨拙的語法。 – 2009-02-09 21:16:04

+5

@hmemcpy:就我個人而言,只要我看到一個布爾常量的比較,就會畏縮。大概是我的C背景展示了......儘管如此,讓我的皮膚爬行,並且我不會讓它獨自留在編輯的代碼中。 – Shog9 2009-02-09 21:17:47

+0

@IgalTabachnik imo如果你打算寫出冗長的邏輯反轉語句,以便清楚地說明它寫得更清晰,就像`if(false == sender is TextBox)` – 2016-10-06 19:13:58

6

你們能不能也做了更詳細的「老」的方式,前is關鍵字:

if (sender.GetType() != typeof(TextBox)) { // ... } 
-1

試試這個。

var cont= textboxobject as Control; 
if(cont.GetType().Name=="TextBox") 
{ 
    MessageBox.show("textboxobject is a textbox"); 
} 
-1

如果您使用繼承,如:

public class BaseClass 
{} 
public class Foo : BaseClass 
{} 
public class Bar : BaseClass 
{} 

... 空性

if (obj?.GetType().BaseType != typeof(Bar)) { // ... } 

if (!(sender is Foo)) { //... } 
1

兩個著名的做這件事的方式是:

1)用的就是運營商:

if (!(sender is TextBox)) {...} 

2),使用操作符(有用的,如果你還需要與文本框實例工作):

var textBox = sender as TextBox; 
if (sender == null) {...}