Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Type.GetEnumUnderlyingType() 메서드 – 열거형의 기저 형식 확인 방법

개요

C#의 Type.GetEnumUnderlyingType() 메서드는 현재 열거형(enum) 타입의 기저 형식(underlying type)을 반환합니다. 열거형은 내부적으로 정수 계열 형식에 멤버 값을 저장하는데, 이 메서드를 사용하면 실제 값이 어떤 형식으로 저장되어 있는지 확인할 수 있습니다. 별도로 지정하지 않은 열거형의 기본 기저 형식은 int(System.Int32)입니다.

구문

메서드의 기본 구문은 다음과 같습니다.

public virtual Type GetEnumUnderlyingType ();

주요 특징

  • 현재 타입이 열거형이 아니면 ArgumentException이 발생합니다.
  • 반환값은 열거형 멤버 값들이 실제로 저장되는 형식입니다.
  • 반사(Reflection)를 통해 동적으로 열거형 정보를 다룰 때 유용하게 사용됩니다.

예제 1: 열거형의 기저 형식 확인

다음은 Type.GetEnumUnderlyingType() 메서드를 사용하는 첫 번째 예제입니다.

using System;
public class Demo {
   enum Vehicle {Car, Bus, Bike, Airplane}
   public static void Main(){
      try {
         Vehicle v = Vehicle.Bike;
         Type type = v.GetType();
         string[] str = type.GetEnumNames();
         Console.WriteLine("GetEnumName() to return the constant name = " + str);
         Type type2 = type.GetEnumUnderlyingType();
         Console.Write("Enum Underlying type = "+type2);
         Console.WriteLine("
Listing constants ..");
         for (int i = 0; i < str.Length; i++)
            Console.Write("{0} ", str[i]);
      }
      catch (ArgumentException e){
         Console.WriteLine("Not an enum!");
         Console.Write("{0}", e.GetType(), e.Message);
      }
   }
}

위 코드를 실행하면 아래와 같은 결과가 출력됩니다.

GetEnumName() to return the constant name = System.String[]
Enum Underlying type = System.Int32
Listing constants ..
Car Bus Bike Airplane

Vehicle 열거형은 별도의 기저 형식을 지정하지 않았기 때문에 기본값인 System.Int32(int)가 반환된 것을 확인할 수 있습니다.

예제 2: 열거형이 아닌 타입에 적용한 경우

이번에는 열거형이 아닌 typeof(int)에 이 메서드를 적용해 보겠습니다.

using System;
public class Demo {
   enum Vehicle {Car, Bus, Bike, Airplane}
   public static void Main(){
      try {
         Type type = typeof(int);
         string[] str = type.GetEnumNames();
         Console.WriteLine("GetEnumName() to return the constant name = " + str);
         Type type2 = type.GetEnumUnderlyingType();
         Console.Write("Enum Underlying type = "+type2);
         Console.WriteLine("
Listing constants ..");
         for (int i = 0; i < str.Length; i++)
            Console.Write("{0} ", str[i]);
      }
      catch (ArgumentException e){
         Console.WriteLine("Not an enum!");
         Console.Write("{0}", e.GetType(), e.Message);
      }
   }
}

실행 결과는 다음과 같습니다.

Not an enum!
System.ArgumentException

int는 열거형이 아니므로 try 블록 안에서 ArgumentException이 발생하고, catch 블록의 예외 처리 코드가 실행된 것을 볼 수 있습니다.

마무리

Type.GetEnumUnderlyingType() 메서드는 열거형이 내부적으로 어떤 형식으로 값을 저장하는지 확인할 때 유용합니다. 반사(Reflection)를 활용해 동적으로 열거형 정보를 처리하는 코드에서 자주 사용되며, 열거형이 아닌 타입에 호출할 경우 ArgumentException이 발생한다는 점만 주의하면 됩니다.