检查对象是否不是类型(!=等效于"IS") - C#

rom*_*n m 65 c# asp.net .net-2.0

这很好用:

    protected void txtTest_Load(object sender, EventArgs e)
    {
        if (sender is TextBox) {...}

    }
Run Code Online (Sandbox Code Playgroud)

有没有办法检查发件人是不是TextBox,某种等同于!= for"is"?

请不要建议将逻辑移到ELSE {} :)

Jon*_*ury 158

这是一种方式:

if (!(sender is TextBox)) {...}
Run Code Online (Sandbox Code Playgroud)

  • @hmemcpy:就个人而言,只要我看到与布尔常量的比较,我就会畏缩.可能我的C背景显示...仍然,让我的皮肤爬行,并且我无法在我正在编辑的代码中单独留下它. (7认同)
  • 对于这种特殊情况,我更喜欢if(sender is TextBox == false).像这样不那么笨重的语法. (4认同)

Ole*_*ukh 9

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

if (sender is not TextBox) {...}
Run Code Online (Sandbox Code Playgroud)

代替

if (!(sender is TextBox)) {...}
Run Code Online (Sandbox Code Playgroud)


Way*_*ina 8

你不能在is关键字之前做更冗长的"旧"方式:

if (sender.GetType() != typeof(TextBox)) { // ... }
Run Code Online (Sandbox Code Playgroud)

  • 当然,您可以,但请注意"is"关键字匹配从TextBox派生的任何对象,而此typeof()检查仅匹配TextBoxes. (11认同)