Check if object is NOT of type (!= equivalent for “IS”) - C#

后端 未结 6 1479
遥遥无期
遥遥无期 2020-12-29 19:16

This works just fine:

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

    }

Is ther

相关标签:
6条回答
  • 2020-12-29 19:41

    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)) { //... }
    
    0 讨论(0)
  • 2020-12-29 19:42

    Couldn't you also do the more verbose "old" way, before the is keyword:

    if (sender.GetType() != typeof(TextBox)) { // ... }
    
    0 讨论(0)
  • 2020-12-29 19:47

    C# 9 allows using the not operator. You can just use

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

    instead of

    if (!(sender is TextBox)) {...}
    
    0 讨论(0)
  • 2020-12-29 19:47

    Try this.

    var cont= textboxobject as Control;
    if(cont.GetType().Name=="TextBox")
    {
       MessageBox.show("textboxobject is a textbox");
    } 
    
    0 讨论(0)
  • 2020-12-29 19:51

    Two well-known ways of doing it are :

    1) Using IS operator:

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

    2) Using AS operator (useful if you also need to work with the textBox instance) :

    var textBox = sender as TextBox;  
    if (sender == null) {...}
    
    0 讨论(0)
  • 2020-12-29 20:00

    This is one way:

    if (!(sender is TextBox)) {...}
    
    0 讨论(0)
提交回复
热议问题