Compruebe si el objeto NO es de tipo (!= equivalente para "IS") - C#


Esto funciona bien:

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

    }

¿Hay una manera de comprobar si el remitente NO es un cuadro de texto, algún tipo de equivalente de != para "es"?

Por favor, no sugieras mover la lógica a ELSE {}:)

Author: Andrew Medico, 2009-02-10

5 answers

Esta es una manera:

if (!(sender is TextBox)) {...}
 137
Author: Jon Tackabury,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-09 21:06:06

¿No podrías hacer también la forma "antigua" más detallada, antes de la palabra clave is:

if (sender.GetType() != typeof(TextBox)) { // ... }
 7
Author: Wayne Molina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-18 08:12:24

Dos formas bien conocidas de hacerlo son:

1) Usando el operador IS:

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

2) Usando COMO operador (útil si también necesita trabajar con la instancia TextBox):

var textBox = sender as TextBox;  
if (sender == null) {...}
 1
Author: John-Philip,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-27 17:56:55

Prueba esto.

var cont= textboxobject as Control;
if(cont.GetType().Name=="TextBox")
{
   MessageBox.show("textboxobject is a textbox");
} 
 -1
Author: Joee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-28 09:39:59

Si usa herencia como:

public class BaseClass
{}
public class Foo : BaseClass
{}
public class Bar : BaseClass
{}

... Null resistente

if (obj?.GetType().BaseType != typeof(Bar)) { // ... }

O

if (!(sender is Foo)) { //... }
 -1
Author: szydzik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-27 11:17:56