programing

개체가 유형이 아닌지 확인(!= "IS"에 해당) - C#

javajsp 2023. 6. 8. 19:23

개체가 유형이 아닌지 확인(!= "IS"에 해당) - C#

이것은 잘 작동합니다.

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

    }

보낸 사람이 텍스트 상자가 아닌지 확인할 수 있는 방법이 있습니까? =("is")와 같은 종류입니다.

논리를 ELSE {}(으)로 이동하는 것을 제안하지 마십시오. :)

이것은 한 가지 방법입니다.

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

C# 9에서는 not 연산자를 사용할 수 없습니다.그냥 사용할 수 있습니다.

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

대신에

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

당신은 또한 더 장황한 "오래된" 방법으로 할 수 없습니까?is키워드:

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

두 가지 잘 알려진 방법은 다음과 같습니다.

IS 연산자 사용:

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

AS 연산자 사용(textBox 인스턴스 작업도 필요한 경우 유용):

var textBox = sender as TextBox;  
if (sender == null) {...}

다음과 같은 상속을 사용하는 경우:

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

Null 저항성

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

또는

if (!(sender is Foo)) { //... }

이거 먹어봐요.

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

언급URL : https://stackoverflow.com/questions/529944/check-if-object-is-not-of-type-equivalent-for-is-c-sharp