检查对象是否不是类型(!=“IS”的等价物)-C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/529944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if object is NOT of type (!= equivalent for "IS") - C#
提问by roman m
This works just fine:
这工作得很好:
protected void txtTest_Load(object sender, EventArgs e)
{
if (sender is TextBox) {...}
}
Is there a way to check if sender is NOT a TextBox, some kind of an equivalent of != for "is"?
有没有办法检查发件人是否不是文本框,某种相当于 != 的“是”?
Please, don't suggest moving the logic to ELSE{} :)
请不要建议将逻辑移至 ELSE{} :)
采纳答案by Jon Tackabury
This is one way:
这是一种方式:
if (!(sender is TextBox)) {...}
回答by Wayne Molina
Couldn't you also do the more verbose "old" way, before the is
keyword:
你难道不能在is
关键字之前做更冗长的“旧”方式:
if (sender.GetType() != typeof(TextBox)) { // ... }
回答by Joee
Try this.
尝试这个。
var cont= textboxobject as Control;
if(cont.GetType().Name=="TextBox")
{
MessageBox.show("textboxobject is a textbox");
}
回答by szydzik
If you use inheritance like:
如果您使用继承,如:
public class BaseClass
{}
public class Foo : BaseClass
{}
public class Bar : BaseClass
{}
... Null resistant
... 抗空
if (obj?.GetType().BaseType != typeof(Bar)) { // ... }
or
或者
if (!(sender is Foo)) { //... }
回答by John-Philip
Two well-known ways of doing it are :
两种众所周知的方法是:
1) Using IS operator:
1) 使用 IS 运算符:
if (!(sender is TextBox)) {...}
2) Using AS operator (useful if you also need to work with the textBox instance) :
2) 使用 AS 运算符(如果您还需要使用 textBox 实例,则很有用):
var textBox = sender as TextBox;
if (sender == null) {...}