Programming

C# - Enum 형의 내부 형식 변경과 유용한 메소드 - byte

DragonTory 2020. 3. 13. 12:51
반응형

1. Enum 타입의 내부 기본 타입 변경 

Enum 변수를 선언 할 때 기본적으로 데이터 형이  Int32 형으로 선언 된다. 

메모리 사용을 조금이라도 줄일기 위해서 숫자가 크지 않는 경우에는 byte를 사용 하고 싶을 때가 있다.

Enum 형의 기본 데이터 형을 변경 하려면 다음과 같이 하면 된다. 

public enum Days : byte

{

Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday

};

 

2. Enum 타입의 내부 기본 타입 얻기

Enum.GetUnderlyingType(enumType);

 

static void DisplayEnumInfo(Enum enumValue)

{

    Type enumType = enumValue.GetType();

    Type underlyingType = Enum.GetUnderlyingType(enumType);

    Console.WriteLine("{0,-10} {1, 18} {2,15}", enumValue, enumType.Name, underlyingType.Name);

}

// The example displays the following output:

// Member Enumeration Underlying Type //

// Red ConsoleColor Int32

// Monday DayOfWeek Int32

// ToEven MidpointRounding Int32

 

3. Enum 리스트를 배열로 얻어 오기

Enum.GetValues(enumType);

 

enum Colors { Red, Green, Blue, Yellow };

foreach(int i in Enum.GetValues(typeof(Colors)))

Console.WriteLine(i);

 

// The example produces the following output:

// The values of the Colors Enum are:

// 0

// 1

// 2

// 3

 

https://docs.microsoft.com/ko-kr/dotnet/api/system.enum.getunderlyingtype?view=netframework-4.8

 

Enum.GetUnderlyingType(Type) 메서드 (System)

 

지정된 열거형의 내부 형식을 반환합니다.Returns the underlying type of t

docs.microsoft.com

https://docs.microsoft.com/ko-kr/dotnet/api/system.enum?view=netframework-4.8

 

Enum 클래스 (System)

 

열거형에 대한 기본 클래스를 제공합니다.Provides the base class for enumerations.

 

docs.microsoft.com

https://docs.microsoft.com/ko-kr/dotnet/api/system.enum.getvalues?view=netframework-4.8

 

Enum.GetValues(Type) 메서드 (System)

 

지정된 열거형에서 상수 값의 배열을 검색합니다.Retrieves an array of the values of

docs.microsoft.com

 

반응형