繁体   English   中英

检查对象是否不是类型(!=“IS”的等价物) - C#

[英]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)) {...}

C# 9 允许使用not运算符。 你可以使用

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

代替

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM