这个很好地运作:
protected void txtTest_Load(object sender, EventArgs e)
{
if (sender is TextBox) {...}
}
有没有一种方法可以检查发送方不是一个TextBox,类似于"is"的"!="的等效方式?请不要建议将逻辑移动到ELSE{}中 :)
这是一种方法:
if (!(sender is TextBox)) {...}
在使用is
关键字之前,您是否也可以使用更冗长的“旧”方法:
if (sender.GetType() != typeof(TextBox)) { // ... }
有两种常见的做法:
1)使用IS运算符:
if (!(sender is TextBox)) {...}
2) 使用AS运算符(如果您也需要使用textBox实例,则很有用):
var textBox = sender as TextBox;
if (sender == null) {...}
is
和 as
的区别可以在这里找到:https://learn.microsoft.com/en-gb/dotnet/csharp/language-reference/operators/type-testing-and-cast - kkuillapublic class BaseClass
{}
public class Foo : BaseClass
{}
public class Bar : BaseClass
{}
...空值(Null)防护
if (obj?.GetType().BaseType != typeof(Bar)) { // ... }
或者
if (!(sender is Foo)) { //... }
试试这个。
var cont= textboxobject as Control;
if(cont.GetType().Name=="TextBox")
{
MessageBox.show("textboxobject is a textbox");
}
as Control
行为与在 object
上使用 GetType()
不同?除此之外,像这样的字符串比较不利于重构友好的代码。 - user247702
if (false == sender is TextBox)
。 - Chris Marisicfalse
比否定更清晰。使用单词is
可能会分散注意力,仅仅浏览代码就很容易错过! - theMayer