检查 object 是否不是类型(! = 等效于“ IS”)-C #

这种方法效果很好:

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


}

有没有一种方法来检查发件人是否不是一个文本框,某种相当于!= “是”的意思?

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

70789 次浏览

This is one way:

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

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

if (sender.GetType() != typeof(TextBox)) { // ... }

Try this.

var cont= textboxobject as Control;
if(cont.GetType().Name=="TextBox")
{
MessageBox.show("textboxobject is a textbox");
}

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)) { //... }

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

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

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

instead of

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