공용 형식 시스템의 열거형

업데이트: 2007년 11월

열거형(enum)은 특수한 값 형식으로서 System.Enum에서 상속되며 내부 기본 형식의 값에 대한 대체 이름을 제공합니다. 열거 형식은 이름, 내부 형식 및 필드의 집합으로 구성됩니다. 내부 형식은 기본으로 제공되는 부호 있는 정수나 부호 없는 정수 형식(Byte, Int32,UInt64 등) 중 하나여야 합니다. 각 필드는 상수를 나타내는 정적 리터럴 필드입니다. 여러 필드에 동일한 값을 할당할 수 있습니다. 이 경우 반영 및 문자열 변환을 위해 값 중 하나를 기본 열거 값으로 표시해야 합니다.

내부 형식의 값을 열거형에 할당하거나 반대로도 할당할 수 있으며 이때 런타임에서 캐스팅할 필요가 없습니다. 열거형의 인스턴스를 만들고 열거의 내부 형식에 정의된 모든 메서드뿐만 아니라 System.Enum의 메서드도 호출할 수 있습니다. 그러나 일부 언어에서는 내부 형식의 인스턴스가 필요한 경우 열거형을 매개 변수로 전달할 수 없고 반대로도 전달할 수 없습니다.

다음은 열거형에 적용되는 추가 제약 조건입니다.

  • 고유의 메서드를 정의할 수 없습니다.

  • 인터페이스를 구현할 수 없습니다.

  • 속성 또는 이벤트를 정의할 수 없습니다.

  • 열거형은 제네릭 형식 내에 중첩되어 있으므로 단독 제네릭이 아니면 제네릭이 될 수 없습니다. 즉, 열거형에는 자체의 형식 매개 변수를 사용할 수 없습니다.

    참고:

    Visual Basic, C# 및 C++를 사용하여 만들어진 중첩 형식(열거형 포함)은 모든 바깥쪽 제네릭 형식의 형식 매개 변수를 포함하므로 그 자체의 형식 매개 변수가 없더라도 제네릭입니다. 자세한 내용은 MakeGenericType의 "중첩 형식"을 참조하십시오.

    MSIL(Microsoft intermediate language) 어셈블리 언어에서 제네릭 열거형을 선언할 수 있지만 열거형을 사용하려고 하면 TypeLoadException이 발생합니다.

Flags 특성은 비트 필드라는 특수한 열거형을 나타냅니다. 런타임 자체에서는 기존의 열거형과 비트 필드를 구분하지 않지만 언어에 따라서는 이를 구분할 수도 있습니다. 이를 구분할 경우 열거형이 아니라 비트 필드에 비트 연산자를 적용하여 명명되지 않은 값을 생성할 수 있습니다. 일반적으로 열거형은 요일, 국가 또는 지역 이름 등과 같은 고유한 요소의 목록에 사용하고, 비트 필드는 Red And Big And Fast 같은 조합에서 나타날 수 있는 특성 및 수량 목록에 사용합니다.

다음 예제에서는 비트 필드와 기존의 열거형을 둘 다 사용하는 방법을 보여 줍니다.

Imports System
Imports System.Collections

' A traditional enumeration of some root vegetables.
Public Enum SomeRootVegetables
    HorseRadish
    Radish
    Turnip
End Enum 'SomeRootVegetables

' A bit field or flag enumeration of harvesting seasons.
<Flags()> Public Enum Seasons
   None = 0
   Summer = 1
   Autumn = 2
   Winter = 4
   Spring = 8
   All = Summer Or Autumn Or Winter Or Spring
End Enum 'Seasons

' Entry point.
Public Class EnumerationSample
    
    Public Shared Sub Main()
        ' Hash table of when vegetables are available.
        Dim AvailableIn As New Hashtable()
        
        AvailableIn(SomeRootVegetables.HorseRadish) = Seasons.All
        AvailableIn(SomeRootVegetables.Radish) = Seasons.Spring
        AvailableIn(SomeRootVegetables.Turnip) = Seasons.Spring Or _
            Seasons.Autumn
        
        ' Array of the seasons, using the enumeration.
        Dim MySeasons() As Seasons = {Seasons.Summer, Seasons.Autumn, _
            Seasons.Winter, Seasons.Spring}
        
        ' Print information of what vegetables are available each season.
        Dim i As Integer
        For i = 0 To MySeasons.Length - 1
            Console.WriteLine( _
                "The following root vegetables are harvested in " _
                & MySeasons(i).ToString("G") & ":")
            Dim e As DictionaryEntry
            For Each e In AvailableIn
                ' A bitwise comparison.
                If(CType(e.Value, Seasons) And MySeasons(i)) > 0 Then
                    Console.WriteLine("  " & _
                        CType(e.Key, SomeRootVegetables).ToString("G"))
                End If
            Next e
        Next i
    End Sub 'Main
End Class 'EnumerationSample
using System;
using System.Collections;

// A traditional enumeration of some root vegetables.
public enum SomeRootVegetables
{
    HorseRadish,
    Radish,
    Turnip
}

// A bit field or flag enumeration of harvesting seasons.
[Flags]
public enum Seasons
{
    None = 0,
    Summer = 1,
    Autumn = 2,
    Winter = 4,
    Spring = 8,
    All = Summer | Autumn | Winter | Spring
}

// Entry point.
public class EnumerationSample
{
    public static void Main()
    {
        // Hash table of when vegetables are available.
        Hashtable AvailableIn = new Hashtable();

        AvailableIn[SomeRootVegetables.HorseRadish] = Seasons.All;
        AvailableIn[SomeRootVegetables.Radish] = Seasons.Spring;
        AvailableIn[SomeRootVegetables.Turnip] = Seasons.Spring | 
            Seasons.Autumn;

        // Array of the seasons, using the enumeration.
        Seasons[] seasons = new Seasons[] { Seasons.Winter, Seasons.Spring, 
            Seasons.Summer, Seasons.Autumn };

        // Print information of what vegetables are available each season.
        for (int i = 0; i < seasons.Length; i++)
        {
            Console.WriteLine(
                "The following root vegetables are harvested in "
                + seasons[i].ToString("G") + ":");
            foreach (DictionaryEntry e in AvailableIn)
            {
                // A bitwise comparison.
                if (((Seasons)e.Value & seasons[i]) > 0)
                    Console.WriteLine("  " +
                        ((SomeRootVegetables)e.Key).ToString("G"));
            }
        }
    }
}

이 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.

The following root vegetables are harvested in Summer:
  HorseRadish
The following root vegetables are harvested in Autumn:
  Turnip
  HorseRadish
The following root vegetables are harvested in Winter:
  HorseRadish
The following root vegetables are harvested in Spring:
  Turnip
  Radish
  HorseRadish

참고 항목

개념

공용 형식 시스템의 값 형식

.NET Framework 클래스 라이브러리 개요

참조

System.ValueType

System.Enum

기타 리소스

공용 형식 시스템