[英]Check if object is NOT of type (!= equivalent for "IS") - C#
这工作得很好:
protected void txtTest_Load(object sender, EventArgs e)
{
if (sender is TextBox) {...}
}
有没有办法检查发件人是否不是文本框,某种相当于 != 的“是”?
请不要建议将逻辑移至 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) {...}
如果您使用继承,如:
public class BaseClass
{}
public class Foo : BaseClass
{}
public class Bar : BaseClass
{}
... 抗空
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.