개발/기본) 기본기

기본기)c#) is 연산자, as 연산자

테샤르 2021. 3. 5. 23:33

is 연산자, as 연산자

 

is 연산자는 자료형 타입 (형식)과 일치하는지 확인하기 위해서 사용한다.

사용 방식은 다음과 같다.  

변수 is 타입으로 선언하게 되면 형식이 맞는지에 대한 return 값 (bool)으로 확인이 가능하다.

using System;

public class Employee : IComparable
{
    public String Name { get; set; }
    public int Id { get; set; }

    public int CompareTo(Object o)
    {
        if (o is Employee e)
        {
            return Name.CompareTo(e.Name);
        }
        throw new ArgumentException("o is not an Employee object.");
    }
}

 

as는 해당 타입을 다른 타입으로 명시적 형 변환 (casting) 할때 필요하다.

 

사용방법은 다음과 같다.

using System;

public class Employee : IComparable
{
    public String Name { get; set; }
    public int Id { get; set; }

    public int CompareTo(Object o)
    {
        Console.WriteLine($"{o.GetType().Name} is not a Mammal");
    }
}

 

형 변환 하는 방법은 여러 가지가 있는데 다음과 같이 형 변환을 하게 되면 예외가 생기기도 한다. 형 변환이 정상적으로 되지 않는 경우 null인 경우 등등에 의거해서 컴파일 에러가 발생한다.

string s = (string)o;

as연산자는 참조, 널 (NULL), 권투, 및 언 박싱 변환을 고려합니다. as연산자를 사용하여 사용자 정의 변환을 수행 할 수 없다.라고 한다.

 

 

참고  Microsoft Doc : [형식 테스트 연산자 및 캐스트 식]

 

Type-testing operators and cast expression - C# reference

Learn about C# operators that you can use to check the type of an expression result and convert it to another type if necessary.

docs.microsoft.com

참고 Microsoft Doc : [as]

 

Expressions - C# language specification

 

docs.microsoft.com

참고 Microsoft Doc : [is]

 

is - C# 참조

is(C# 참조)is (C# Reference) 이 문서의 내용 --> is 연산자는 식의 결과가 지정된 형식과 호환되는지 확인하거나, (C# 7.0부터) 패턴에 대해 식을 테스트합니다.The is operator checks if the result of an expression is

docs.microsoft.com

 

 

★☆

 

반응형