Check if object is NOT of type (!= equivalent for

2020-02-24 04:56发布

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{} :)

5条回答
▲ chillily
2楼-- · 2020-02-24 05:29

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) {...}
查看更多
劳资没心,怎么记你
3楼-- · 2020-02-24 05:36

Try this.

var cont= textboxobject as Control;
if(cont.GetType().Name=="TextBox")
{
   MessageBox.show("textboxobject is a textbox");
} 
查看更多
4楼-- · 2020-02-24 05:38

This is one way:

if (!(sender is TextBox)) {...}
查看更多
劳资没心,怎么记你
5楼-- · 2020-02-24 05:41

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

if (sender.GetType() != typeof(TextBox)) { // ... }
查看更多
一纸荒年 Trace。
6楼-- · 2020-02-24 05:49

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)) { //... }
查看更多
登录 后发表回答