System.Enum 클래스

이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.

열거형은 기본 형식이 모든 정수 형식인 명명된 상수 집합입니다. 명시적으로 선언된 Int32 기본 형식이 없으면 사용됩니다. Enum 는 .NET의 모든 열거형에 대한 기본 클래스입니다. 열거형 형식은 C#의 enum 키워드(keyword) Visual Basic의 Enum...End Enum 구문 및 F#의 type 키워드(keyword) 의해 정의됩니다.

Enum 에서는 이 클래스의 인스턴스를 비교하고, 인스턴스 값을 문자열 표현으로 변환하고, 숫자의 문자열 표현을 이 클래스의 인스턴스로 변환하고, 지정된 열거형 및 값의 인스턴스를 만드는 메서드를 제공합니다.

열거형을 비트 필드로 처리할 수도 있습니다. 자세한 내용은 비독점 멤버 및 Flags 특성 섹션을 참조하세요FlagsAttribute.

열거형 형식 만들기

프로그래밍 언어는 일반적으로 명명된 상수 집합과 해당 값으로 구성된 열거형을 선언하는 구문을 제공합니다. 다음 예제에서는 C#, F# 및 Visual Basic에서 열거형을 정의하는 데 사용하는 구문을 보여 줍니다. 세 개의 멤버ArrivalStatus.Early가 있는 명명 ArrivalStatus 된 열거형을 ArrivalStatus.OnTimeArrivalStatus.Late만듭니다. 모든 경우에 열거형은 명시적으로 상속 Enum되지 않으며 상속 관계는 컴파일러에서 암시적으로 처리됩니다.

public enum ArrivalStatus { Unknown=-3, Late=-1, OnTime=0, Early=1 };
type ArrivalStatus =
    | Late = -1
    | OnTime = 0
    | Early = 1
Public Enum ArrivalStatus1 As Integer
    Late = -1
    OnTime = 0
    Early = 1
End Enum

Warning

내부 형식이 정수 형식이 아니거나 Char열거형 형식을 만들면 안 됩니다. 리플렉션을 사용하여 이러한 열거형 형식을 만들 수 있지만 결과 형식을 사용하는 메서드 호출은 신뢰할 수 없으며 추가 예외를 throw할 수도 있습니다.

열거형 형식 인스턴스화

변수를 선언하고 열거형의 상수 중 하나를 할당하여 다른 값 형식을 인스턴스화하는 것처럼 열거형 형식을 인스턴스화할 수 있습니다. 다음 예제에서는 값을 ArrivalStatus.OnTime인스턴스화 ArrivalStatus 합니다.

public class Example
{
   public static void Main()
   {
      ArrivalStatus status = ArrivalStatus.OnTime;
      Console.WriteLine("Arrival Status: {0} ({0:D})", status);
   }
}
// The example displays the following output:
//       Arrival Status: OnTime (0)
let status = ArrivalStatus.OnTime
printfn $"Arrival Status: {status} ({status:D})"
// The example displays the following output:
//       Arrival Status: OnTime (0)
Public Module Example1
    Public Sub Main()
        Dim status As ArrivalStatus1 = ArrivalStatus1.OnTime
        Console.WriteLine("Arrival Status: {0} ({0:D})", status)
    End Sub
End Module
' The example displays the following output:
'        Arrival Status: OnTime (0)

다음과 같은 방법으로 열거형 값을 인스턴스화할 수도 있습니다.

  • 특정 프로그래밍 언어의 기능을 사용하여 C#에서와 같이 캐스팅하거나(Visual Basic에서와 같이) 정수 값을 열거형 값으로 변환합니다. 다음 예제에서는 값 ArrivalStatus.EarlyArrivalStatus 이런 방식으로 개체를 만듭니다.

    ArrivalStatus status2 = (ArrivalStatus)1;
    Console.WriteLine("Arrival Status: {0} ({0:D})", status2);
    // The example displays the following output:
    //       Arrival Status: Early (1)
    
    let status2 = enum<ArrivalStatus> 1
    printfn $"Arrival Status: {status2} ({status2:D})"
    // The example displays the following output:
    //       Arrival Status: Early (1)
    
    Dim status2 As ArrivalStatus2 = CType(1, ArrivalStatus2)
    Console.WriteLine("Arrival Status: {0} ({0:D})", status2)
    ' The example displays the following output:
    '       Arrival Status: Early (1)
    
  • 암시적 매개 변수 없는 생성자를 호출합니다. 다음 예제와 같이 이 경우 열거형 인스턴스의 기본 값은 0입니다. 그러나 열거형에서 유효한 상수의 값이 반드시 있는 것은 아닙니다.

    ArrivalStatus status1 = new ArrivalStatus();
    Console.WriteLine("Arrival Status: {0} ({0:D})", status1);
    // The example displays the following output:
    //       Arrival Status: OnTime (0)
    
    let status1 = ArrivalStatus()
    printfn $"Arrival Status: {status1} ({status1:D})"
    // The example displays the following output:
    //       Arrival Status: OnTime (0)
    
    Dim status1 As New ArrivalStatus2()
    Console.WriteLine("Arrival Status: {0} ({0:D})", status1)
    ' The example displays the following output:
    '        Arrival Status: OnTime (0)
    
  • 열거형에서 Parse 상수의 이름을 포함하는 문자열을 구문 분석하기 위해 또는 TryParse 메서드를 호출합니다. 자세한 내용은 구문 분석 열거형 값 섹션을 참조 하세요 .

  • 정수 값을 열거형 형식으로 변환하는 메서드를 호출 ToObject 합니다. 자세한 내용은 변환 수행 섹션을 참조하세요 .

열거형 모범 사례

열거형 형식을 정의할 때는 다음 모범 사례를 사용하는 것이 좋습니다.

  • 값이 0인 열거형 멤버를 정의하지 않은 경우 열거형 상수 만들기를 None 고려합니다. 기본적으로 열거형에 사용되는 메모리는 공용 언어 런타임에 의해 0으로 초기화됩니다. 따라서 값이 0인 상수는 정의하지 않으면 열거형을 만들 때 잘못된 값이 포함됩니다.

  • 나타내는 열거형을 사용 하 여 애플리케이션에 명확한 기본 사례를 경우 상수 값이 0 인 나타내야 합니다. 기본 사례가 없는 경우 값이 0인 열거형 상수를 사용하여 열거된 다른 상수로 표현되지 않는 대/소문자를 지정하는 것이 좋습니다.

  • 나중에 사용하도록 예약된 열거형 상수를 지정하지 마세요.

  • 열거형 상수 값을 값으로 사용하는 메서드 또는 속성을 정의할 때 값의 유효성을 검사하는 것이 좋습니다. 그 이유는 해당 숫자 값이 열거형에 정의되지 않은 경우에도 숫자 값을 열거형 형식으로 캐스팅할 수 있기 때문입니다.

비독점 멤버 및 Flags 특성 섹션에 상수가 비트 필드인 열거형 형식에 대한 추가 모범 사례입니다.

열거형을 사용하여 작업 수행

열거형을 만들 때는 새 메서드를 정의할 수 없습니다. 그러나 열거형 형식은 클래스에서 정적 및 인스턴스 메서드의 전체 집합을 상속합니다 Enum . 다음 섹션에서는 열거형 값을 사용할 때 일반적으로 사용되는 몇 가지 다른 메서드 외에도 이러한 메서드의 대부분을 조사합니다.

변환 수행

캐스팅(C# 및 F#) 또는 변환(Visual Basic) 연산자를 사용하여 열거형 멤버와 해당 기본 형식 간에 변환할 수 있습니다. F#에서도 enum 함수가 사용됩니다. 다음 예제에서는 캐스팅 또는 변환 연산자를 사용하여 정수에서 열거형 값으로, 열거형 값에서 정수로 변환을 수행합니다.

int value3 = 2;
ArrivalStatus status3 = (ArrivalStatus)value3;

int value4 = (int)status3;
let value3 = 2
let status3 = enum<ArrivalStatus> value3

let value4 = int status3
Dim value3 As Integer = 2
Dim status3 As ArrivalStatus2 = CType(value3, ArrivalStatus2)

Dim value4 As Integer = CInt(status3)

클래스에는 Enum 정수 계열 형식의 값을 열거형 값으로 변환하는 메서드도 포함 ToObject 됩니다. 다음 예제에서는 메서드를 ToObject(Type, Int32) 사용하여 값을 변환 Int32 합니다 ArrivalStatus . ToObject 형식 값을 반환하므로 개체를 열거형 형식Object으로 캐스팅하는 데 캐스팅 또는 변환 연산자를 사용해야 할 수도 있습니다.

int number = -1;
ArrivalStatus arrived = (ArrivalStatus)ArrivalStatus.ToObject(typeof(ArrivalStatus), number);
let number = -1
let arrived = ArrivalStatus.ToObject(typeof<ArrivalStatus>, number) :?> ArrivalStatus
Dim number As Integer = -1
Dim arrived As ArrivalStatus2 = CType(ArrivalStatus2.ToObject(GetType(ArrivalStatus2), number), ArrivalStatus2)

정자를 열거형 값으로 변환할 때 실제로 열거형의 멤버가 아닌 값을 할당할 수 있습니다. 이를 방지하기 위해 변환을 수행하기 전에 정수를 IsDefined 메서드에 전달할 수 있습니다. 다음 예제에서는 이 메서드를 사용하여 정수 값 배열의 요소를 값으로 변환 ArrivalStatus 할 수 있는지 여부를 확인합니다.

using System;

public class Example3
{
    public static void Main()
    {
        int[] values = { -3, -1, 0, 1, 5, Int32.MaxValue };
        foreach (var value in values)
        {
            ArrivalStatus status;
            if (Enum.IsDefined(typeof(ArrivalStatus), value))
                status = (ArrivalStatus)value;
            else
                status = ArrivalStatus.Unknown;
            Console.WriteLine("Converted {0:N0} to {1}", value, status);
        }
    }
}
// The example displays the following output:
//       Converted -3 to Unknown
//       Converted -1 to Late
//       Converted 0 to OnTime
//       Converted 1 to Early
//       Converted 5 to Unknown
//       Converted 2,147,483,647 to Unknown
open System

type ArrivalStatus =
    | Unknown = -3
    | Late = -1
    | OnTime = 0
    | Early = 1

let values = [ -3; -1; 0; 1; 5; Int32.MaxValue ]
for value in values do
    let status =
        if Enum.IsDefined(typeof<ArrivalStatus>, value) then
            enum value
        else
            ArrivalStatus.Unknown
    printfn $"Converted {value:N0} to {status}"
// The example displays the following output:
//       Converted -3 to Unknown
//       Converted -1 to Late
//       Converted 0 to OnTime
//       Converted 1 to Early
//       Converted 5 to Unknown
//       Converted 2,147,483,647 to Unknown
Public Enum ArrivalStatus4 As Integer
    Unknown = -3
    Late = -1
    OnTime = 0
    Early = 1
End Enum

Module Example4
    Public Sub Main()
        Dim values() As Integer = {-3, -1, 0, 1, 5, Int32.MaxValue}
        For Each value In values
            Dim status As ArrivalStatus4
            If [Enum].IsDefined(GetType(ArrivalStatus4), value) Then
                status = CType(value, ArrivalStatus4)
            Else
                status = ArrivalStatus4.Unknown
            End If
            Console.WriteLine("Converted {0:N0} to {1}", value, status)
        Next
    End Sub
End Module
' The example displays the following output:
'       Converted -3 to Unknown
'       Converted -1 to Late
'       Converted 0 to OnTime
'       Converted 1 to Early
'       Converted 5 to Unknown
'       Converted 2,147,483,647 to Unknown

클래스는 Enum 열거형 값에서 정수 형식으로 변환하기 위한 인터페이스의 IConvertible 명시적 인터페이스 구현을 제공하지만 이러한 변환을 수행하려면 클래스의 Convert 메서드(예: ToInt32메서드)를 사용해야 합니다. 다음 예제에서는 메서드와 함께 Convert.ChangeType 메서드를 사용하여 GetUnderlyingType 열거형 값을 기본 형식으로 변환하는 방법을 보여 줍니다. 이 예제에서는 컴파일 시간에 열거형의 기본 형식을 알 필요가 없습니다.

ArrivalStatus status = ArrivalStatus.Early;
var number = Convert.ChangeType(status, Enum.GetUnderlyingType(typeof(ArrivalStatus)));
Console.WriteLine("Converted {0} to {1}", status, number);
// The example displays the following output:
//       Converted Early to 1
let status = ArrivalStatus.Early
let number = Convert.ChangeType(status, Enum.GetUnderlyingType typeof<ArrivalStatus>)
printfn $"Converted {status} to {number}"
// The example displays the following output:
//       Converted Early to 1
Dim status As ArrivalStatus5 = ArrivalStatus5.Early
Dim number = Convert.ChangeType(status, [Enum].GetUnderlyingType(GetType(ArrivalStatus5)))
Console.WriteLine("Converted {0} to {1}", status, number)
' The example displays the following output:
'       Converted Early to 1

열거형 값 구문 분석

ParseTryParse 메서드를 사용하면 열거형 값의 문자열 표현을 해당 값으로 변환할 수 있습니다. 문자열 표현은 열거형 상수의 이름 또는 기본 값일 수 있습니다. 문자열을 열거형의 기본 형식 값으로 변환할 수 있는 경우 구문 분석 메서드는 특정 열거형의 멤버가 아닌 숫자의 문자열 표현을 성공적으로 변환합니다. 이를 IsDefined 방지하기 위해 구문 분석 메서드의 결과가 유효한 열거형 값인지 확인하기 위해 메서드를 호출할 수 있습니다. 이 예제에서는 이 방법을 보여 줍니다. 및 메서드에 대한 호출을 Parse(Type, String)Enum.TryParse<TEnum>(String, TEnum) 보여 줍니다. 제네릭이 아닌 구문 분석 메서드는 C# 및 F#으로 캐스팅하거나(Visual Basic에서) 적절한 열거형 형식으로 변환해야 할 수 있는 개체를 반환합니다.

string number = "-1";
string name = "Early";

try
{
    ArrivalStatus status1 = (ArrivalStatus)Enum.Parse(typeof(ArrivalStatus), number);
    if (!(Enum.IsDefined(typeof(ArrivalStatus), status1)))
        status1 = ArrivalStatus.Unknown;
    Console.WriteLine("Converted '{0}' to {1}", number, status1);
}
catch (FormatException)
{
    Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.",
                      number);
}

ArrivalStatus status2;
if (Enum.TryParse<ArrivalStatus>(name, out status2))
{
    if (!(Enum.IsDefined(typeof(ArrivalStatus), status2)))
        status2 = ArrivalStatus.Unknown;
    Console.WriteLine("Converted '{0}' to {1}", name, status2);
}
else
{
    Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.",
                      number);
}
// The example displays the following output:
//       Converted '-1' to Late
//       Converted 'Early' to Early
let number = "-1"
let name = "Early"

try
    let status1 = Enum.Parse(typeof<ArrivalStatus>, number) :?> ArrivalStatus
    let status1 =
        if not (Enum.IsDefined(typeof<ArrivalStatus>, status1) ) then
            ArrivalStatus.Unknown
        else 
            status1
        
    printfn $"Converted '{number}' to {status1}"
with :? FormatException ->
    printfn $"Unable to convert '{number}' to an ArrivalStatus value."

match Enum.TryParse<ArrivalStatus> name with
| true, status2 ->
    let status2 = 
        if not (Enum.IsDefined(typeof<ArrivalStatus>, status2) ) then
            ArrivalStatus.Unknown
        else 
            status2
    printfn $"Converted '{name}' to {status2}"
| _ ->
    printfn $"Unable to convert '{number}' to an ArrivalStatus value."
// The example displays the following output:
//       Converted '-1' to Late
//       Converted 'Early' to Early
Dim number As String = "-1"
Dim name As String = "Early"
Dim invalid As String = "32"

Try
    Dim status1 As ArrivalStatus8 = CType([Enum].Parse(GetType(ArrivalStatus8), number), ArrivalStatus8)
    If Not [Enum].IsDefined(GetType(ArrivalStatus8), status1) Then status1 = ArrivalStatus8.Unknown
    Console.WriteLine("Converted '{0}' to {1}", number, status1)
Catch e As FormatException
    Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus8 value.",
                   number)
End Try

Dim status2 As ArrivalStatus8
If [Enum].TryParse(Of ArrivalStatus8)(name, status2) Then
    If Not [Enum].IsDefined(GetType(ArrivalStatus8), status2) Then status2 = ArrivalStatus8.Unknown
    Console.WriteLine("Converted '{0}' to {1}", name, status2)
Else
    Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus8 value.",
                   number)
End If
' The example displays the following output:
'       Converted '-1' to Late
'       Converted 'Early' to Early

열거형 값 서식 지정

정적 Format 메서드와 인스턴스 ToString 메서드의 오버로드를 호출하여 열거형 값을 문자열 표현으로 변환할 수 있습니다. 형식 문자열을 사용하여 열거형 값이 문자열로 표시되는 정확한 방법을 제어할 수 있습니다. 자세한 내용은 열거형 형식 문자열을 참조하세요. 다음 예제에서는 지원되는 각 열거형 형식 문자열("G" 또는 "g", "D" 또는 "d", "X" 또는 "x" 및 "F" 또는 "f")을 사용하여 열거형의 ArrivalStatus 멤버를 해당 문자열 표현으로 변환합니다.

string[] formats = { "G", "F", "D", "X" };
ArrivalStatus status = ArrivalStatus.Late;
foreach (var fmt in formats)
    Console.WriteLine(status.ToString(fmt));

// The example displays the following output:
//       Late
//       Late
//       -1
//       FFFFFFFF
let formats = [ "G"; "F"; "D"; "X" ]
let status = ArrivalStatus.Late
for fmt in formats do
    printfn $"{status.ToString fmt}"

// The example displays the following output:
//       Late
//       Late
//       -1
//       FFFFFFFF
Dim formats() As String = {"G", "F", "D", "X"}
Dim status As ArrivalStatus6 = ArrivalStatus6.Late
For Each fmt As String In formats
    Console.WriteLine(status.ToString(fmt))
Next
' The example displays the following output:
'       Late
'       Late
'       -1
'       FFFFFFFF

열거형 멤버 반복

형식은 Enum (C#), (F#), for..in 또는 For Each (Visual Basic에서) 구문을 사용하여 foreach 컬렉션의 멤버를 반복할 수 있도록 하는 또는 IEnumerable<T> 인터페이스를 구현 IEnumerable 하지 않습니다. 그러나 두 가지 방법 중 하나를 사용하여 멤버를 열거할 수 있습니다.

  • 메서드를 GetNames 호출하여 열거형 멤버의 이름을 포함하는 문자열 배열을 검색할 수 있습니다. 다음으로 문자열 배열의 각 요소에 대해 메서드를 Parse 호출하여 문자열을 해당하는 열거형 값으로 변환할 수 있습니다. 다음 예제에서 이 방법을 보여 줍니다.

    string[] names = Enum.GetNames(typeof(ArrivalStatus));
    Console.WriteLine("Members of {0}:", typeof(ArrivalStatus).Name);
    Array.Sort(names);
    foreach (var name in names)
    {
        ArrivalStatus status = (ArrivalStatus)Enum.Parse(typeof(ArrivalStatus), name);
        Console.WriteLine("   {0} ({0:D})", status);
    }
    // The example displays the following output:
    //       Members of ArrivalStatus:
    //          Early (1)
    //          Late (-1)
    //          OnTime (0)
    //          Unknown (-3)
    
    let names = Enum.GetNames typeof<ArrivalStatus>
    printfn $"Members of {nameof ArrivalStatus}:"
    let names = Array.sort names
    for name in names do
        let status = Enum.Parse(typeof<ArrivalStatus>, name) :?> ArrivalStatus
        printfn $"   {status} ({status:D})"
    // The example displays the following output:
    //       Members of ArrivalStatus:
    //          Early (1)
    //          Late (-1)
    //          OnTime (0)
    //          Unknown (-3)
    
    Dim names() As String = [Enum].GetNames(GetType(ArrivalStatus7))
    Console.WriteLine("Members of {0}:", GetType(ArrivalStatus7).Name)
    Array.Sort(names)
    For Each name In names
        Dim status As ArrivalStatus7 = CType([Enum].Parse(GetType(ArrivalStatus7), name),
                                   ArrivalStatus7)
        Console.WriteLine("   {0} ({0:D})", status)
    Next
    ' The example displays the following output:
    '       Members of ArrivalStatus7:
    '          Early (1)
    '          Late (-1)
    '          OnTime (0)
    '          Unknown (-3)
    
  • 메서드를 GetValues 호출하여 열거형의 기본 값이 포함된 배열을 검색할 수 있습니다. 다음으로 배열의 각 요소에 대해 메서드를 ToObject 호출하여 정수를 해당하는 열거형 값으로 변환할 수 있습니다. 다음 예제에서 이 방법을 보여 줍니다.

    var values = Enum.GetValues(typeof(ArrivalStatus));
    Console.WriteLine("Members of {0}:", typeof(ArrivalStatus).Name);
    foreach (ArrivalStatus status in values)
    {
        Console.WriteLine("   {0} ({0:D})", status);
    }
    // The example displays the following output:
    //       Members of ArrivalStatus:
    //          OnTime (0)
    //          Early (1)
    //          Unknown (-3)
    //          Late (-1)
    
    let values = Enum.GetValues typeof<ArrivalStatus>
    printfn $"Members of {nameof ArrivalStatus}:"
    for status in values do
        printfn $"   {status} ({status:D})"
    // The example displays the following output:
    //       Members of ArrivalStatus:
    //          OnTime (0)
    //          Early (1)
    //          Unknown (-3)
    //          Late (-1)
    
    Dim values = [Enum].GetValues(GetType(ArrivalStatus7))
    Console.WriteLine("Members of {0}:", GetType(ArrivalStatus7).Name)
    For Each value In values
        Dim status As ArrivalStatus7 = CType([Enum].ToObject(GetType(ArrivalStatus7), value),
                                         ArrivalStatus7)
        Console.WriteLine("   {0} ({0:D})", status)
    Next
    ' The example displays the following output:
    '       Members of ArrivalStatus7:
    '          OnTime (0)
    '          Early (1)
    '          Unknown (-3)
    '          Late (-1)
    

비독점 멤버 및 Flags 특성

열거형의 일반적인 용도 중 하나는 상호 배타적인 값 집합을 나타내는 것입니다. 예를 들어 인스턴스의 ArrivalStatusEarly은 , OnTime또는 Late. 인스턴스 값 ArrivalStatus 이 둘 이상의 열거형 상수에 반영되는 것은 의미가 없습니다.

그러나 열거형 개체의 값에는 여러 열거형 멤버가 포함될 수 있으며 각 멤버는 열거형 값의 비트 필드를 나타냅니다. 이 FlagsAttribute 특성을 사용하여 열거형이 비트 필드로 구성됨을 나타낼 수 있습니다. 예를 들어, 명명 Pets 된 열거형을 사용하여 가정에서 애완 동물의 종류를 나타낼 수 있습니다. 다음과 같이 정의할 수 있습니다.

[Flags]
public enum Pets
{
    None = 0, Dog = 1, Cat = 2, Bird = 4, Rodent = 8,
    Reptile = 16, Other = 32
};
[<Flags>] 
type Pets =
    | None = 0
    | Dog = 1
    | Cat = 2
    | Bird = 4
    | Rodent = 8
    | Reptile = 16
    | Other = 32
<Flags> Public Enum Pets As Integer
   None = 0
   Dog = 1
   Cat = 2
   Bird = 4
   Rodent = 8
   Reptile = 16
   Other = 32
End Enum

Pets 그런 다음, 다음 예제와 같이 열거형을 사용할 수 있습니다.

Pets familyPets = Pets.Dog | Pets.Cat;
Console.WriteLine("Pets: {0:G} ({0:D})", familyPets);
// The example displays the following output:
//       Pets: Dog, Cat (3)
let familyPets = Pets.Dog ||| Pets.Cat
printfn $"Pets: {familyPets:G} ({familyPets:D})"
// The example displays the following output:
//       Pets: Dog, Cat (3)
Dim familyPets As Pets = Pets.Dog Or Pets.Cat
Console.WriteLine("Pets: {0:G} ({0:D})", familyPets)
' The example displays the following output:
'       Pets: Dog, Cat (3)

비트 열거형을 정의하고 특성을 적용 FlagsAttribute 할 때는 다음 모범 사례를 사용해야 합니다.

  • FlagsAttribute 숫자 값에 대해 비트 연산(AND, OR, EXCLUSIVE OR)을 수행해야 하는 경우에만 열거형에 사용자 지정 특성을 사용합니다.

  • 열거형 상수(1, 2, 4, 8 등)를 2의 권한으로 정의합니다. 즉, 결합된 열거형 상수의 개별 플래그가 겹치지 않습니다.

  • 일반적으로 사용되는 플래그 조합에 대해 열거형 상수 만들기를 고려합니다. 예를 들어 열거된 상수가 포함된 파일 I/O 작업에 사용되는 열거형이 있는 경우 열거형 상 Read = 1 수와 Write = 2Write 플래그를 결합하는 열거형 상수 ReadWrite = Read OR Write만들기를 고려합니다Read. 또한 플래그를 결합하는 데 사용되는 비트 OR 연산은 간단한 작업에 필요하지 않은 경우에 고급 개념으로 간주될 수 있습니다.

  • 많은 플래그 위치가 1로 설정될 수 있으므로 음수를 플래그 열거 상수로 정의하면 코드가 혼동되고 코딩 오류가 발생할 수 있으므로 주의해야 합니다.

  • 플래그가 숫자 값에 설정되어 있는지 여부를 테스트하는 편리한 방법은 다음 예제와 같이 인스턴스 HasFlag 메서드를 호출하는 것입니다.

    Pets familyPets = Pets.Dog | Pets.Cat;
    if (familyPets.HasFlag(Pets.Dog))
        Console.WriteLine("The family has a dog.");
    // The example displays the following output:
    //       The family has a dog.
    
    let familyPets = Pets.Dog ||| Pets.Cat
    if familyPets.HasFlag Pets.Dog then
        printfn "The family has a dog."
    // The example displays the following output:
    //       The family has a dog.
    
    Dim familyPets As Pets = Pets.Dog Or Pets.Cat
    If familyPets.HasFlag(Pets.Dog) Then
        Console.WriteLine("The family has a dog.")
    End If
    ' The example displays the following output:
    '       The family has a dog.
    

    숫자 값과 플래그 열거형 상수 간에 비트 AND 연산을 수행하는 것과 같습니다. 이 상수는 숫자 값의 모든 비트를 플래그에 해당하지 않는 0으로 설정한 다음, 해당 작업의 결과가 플래그 열거 상수와 같은지 여부를 테스트합니다. 다음 예에서 확인할 수 있습니다.

    Pets familyPets = Pets.Dog | Pets.Cat;
    if ((familyPets & Pets.Dog) == Pets.Dog)
        Console.WriteLine("The family has a dog.");
    // The example displays the following output:
    //       The family has a dog.
    
    let familyPets = Pets.Dog ||| Pets.Cat
    if (familyPets &&& Pets.Dog) = Pets.Dog then
        printfn "The family has a dog."
    // The example displays the following output:
    //       The family has a dog.
    
    Dim familyPets As Pets = Pets.Dog Or Pets.Cat
    If familyPets And Pets.Dog = Pets.Dog Then
        Console.WriteLine("The family has a dog.")
    End If
    ' The example displays the following output:
    '       The family has a dog.
    
  • 값이 0인 플래그 열거형 상수의 이름으로 사용합니다 None . 결과가 항상 0이므로 비트 AND 연산에서 열거형 상수로 플래그를 테스트할 수 없습니다 None . 그러나 숫자 값과 None 열거된 상수 간의 비트 비교가 아닌 논리적 비교를 수행하여 숫자 값의 비트가 설정되었는지 여부를 확인할 수 있습니다. 다음 예에서 확인할 수 있습니다.

    Pets familyPets = Pets.Dog | Pets.Cat;
    if (familyPets == Pets.None)
        Console.WriteLine("The family has no pets.");
    else
        Console.WriteLine("The family has pets.");
    // The example displays the following output:
    //       The family has pets.
    
    let familyPets = Pets.Dog ||| Pets.Cat
    if familyPets = Pets.None then
        printfn "The family has no pets."
    else
        printfn "The family has pets."
    // The example displays the following output:
    //       The family has pets.
    
    Dim familyPets As Pets = Pets.Dog Or Pets.Cat
    If familyPets = Pets.None Then
        Console.WriteLine("The family has no pets.")
    Else
        Console.WriteLine("The family has pets.")
    End If
    ' The example displays the following output:
    '       The family has pets.
    
  • 열거형 자체의 상태를 미러 위해서만 열거형 값을 정의하지 마세요. 예를 들어 열거형의 끝을 표시하는 열거형 상수만 정의하지 마세요. 열거형의 마지막 값을 결정해야 하는 경우 해당 값에 대해 명시적으로 검사. 또한 범위 내의 모든 값이 유효한 경우 첫 번째 및 마지막 열거형 상수에 대한 범위 검사 수행할 수 있습니다.

열거형 메서드 추가

열거형 형식은 (C#) 및 (Visual Basic) 같은 enumEnum 언어 구조에 의해 정의되므로 클래스에서 Enum 상속된 메서드 이외의 열거형 형식에 대한 사용자 지정 메서드를 정의할 수 없습니다. 그러나 확장 메서드를 사용하여 특정 열거형 형식에 기능을 추가할 수 있습니다.

다음 예제에서 Grades 열거형은 학생이 클래스에서 받을 수 있는 문자 성적을 나타냅니다. 해당 형식의 각 인스턴스가 이제 합격 성적을 나타내는지 여부를 "알 수 있도록" Passing이라는 확장 메서드가 Grades 형식에 추가됩니다. 클래스에는 Extensions 최소 통과 등급을 정의하는 정적 읽기-쓰기 변수도 포함됩니다. 확장 메서드의 Passing 반환 값은 해당 변수의 현재 값을 반영합니다.

using System;

// Define an enumeration to represent student grades.
public enum Grades { F = 0, D = 1, C = 2, B = 3, A = 4 };

// Define an extension method for the Grades enumeration.
public static class Extensions
{
    public static Grades minPassing = Grades.D;

    public static bool Passing(this Grades grade)
    {
        return grade >= minPassing;
    }
}

class Example8
{
    static void Main()
    {
        Grades g1 = Grades.D;
        Grades g2 = Grades.F;
        Console.WriteLine("{0} {1} a passing grade.", g1, g1.Passing() ? "is" : "is not");
        Console.WriteLine("{0} {1} a passing grade.", g2, g2.Passing() ? "is" : "is not");

        Extensions.minPassing = Grades.C;
        Console.WriteLine("\nRaising the bar!\n");
        Console.WriteLine("{0} {1} a passing grade.", g1, g1.Passing() ? "is" : "is not");
        Console.WriteLine("{0} {1} a passing grade.", g2, g2.Passing() ? "is" : "is not");
    }
}
// The exmaple displays the following output:
//       D is a passing grade.
//       F is not a passing grade.
//
//       Raising the bar!
//
//       D is not a passing grade.
//       F is not a passing grade.
open System
open System.Runtime.CompilerServices
// Define an enumeration to represent student grades.
type Grades =
    | F = 0
    | D = 1
    | C = 2
    | B = 3
    | A = 4

let mutable minPassing = Grades.D

// Define an extension method for the Grades enumeration.
[<Extension>]
type Extensions =
    [<Extension>]
    static member Passing(grade) = grade >= minPassing

let g1 = Grades.D
let g2 = Grades.F
printfn $"""{g1} {if g1.Passing() then "is" else "is not"} a passing grade."""
printfn $"""{g2} {if g2.Passing() then "is" else "is not"} a passing grade."""

minPassing <- Grades.C
printfn "\nRaising the bar!\n"
printfn $"""{g1} {if g1.Passing() then "is" else "is not"} a passing grade."""
printfn $"""{g2} {if g2.Passing() then "is" else "is not"} a passing grade."""
// The exmaple displays the following output:
//       D is a passing grade.
//       F is not a passing grade.
//
//       Raising the bar!
//
//       D is not a passing grade.
//       F is not a passing grade.
Imports System.Runtime.CompilerServices

' Define an enumeration to represent student grades.
Public Enum Grades As Integer
   F = 0
   D = 1
   C = 2
   B = 3
   A = 4
End Enum   

' Define an extension method for the Grades enumeration.
Public Module Extensions
  Public minPassing As Grades = Grades.D
 
  <Extension>
  Public Function Passing(grade As Grades) As Boolean
     Return grade >= minPassing
  End Function
End Module

Public Module Example
  Public Sub Main()
      Dim g1 As Grades = Grades.D
      Dim g2 As Grades = Grades.F
      Console.WriteLine("{0} {1} a passing grade.", 
                        g1, If(g1.Passing(), "is", "is not"))
      Console.WriteLine("{0} {1} a passing grade.", 
                        g2, If(g2.Passing(), "is", "is not"))
      Console.WriteLine()
      
      Extensions.minPassing = Grades.C
      Console.WriteLine("Raising the bar!")
      Console.WriteLine()
      Console.WriteLine("{0} {1} a passing grade.", 
                        g1, If(g1.Passing(), "is", "is not"))
      Console.WriteLine("{0} {1} a passing grade.", 
                        g2, If(g2.Passing(), "is", "is not"))
  End Sub
End Module
' The exmaple displays the following output:
'       D is a passing grade.
'       F is not a passing grade.
'       
'       Raising the bar!
'       
'       D is not a passing grade.
'       F is not a passing grade.

예제

다음 예제에서는 열거형을 사용하여 명명된 값을 나타내고 다른 열거형을 사용하여 명명된 비트 필드를 나타내는 방법을 보여 줍니다.

using System;

public class EnumTest {
    enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
    enum BoilingPoints { Celsius = 100, Fahrenheit = 212 };
    [Flags]
    enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

    public static void Main() {

        Type weekdays = typeof(Days);
        Type boiling = typeof(BoilingPoints);

        Console.WriteLine("The days of the week, and their corresponding values in the Days Enum are:");

        foreach ( string s in Enum.GetNames(weekdays) )
            Console.WriteLine( "{0,-11}= {1}", s, Enum.Format( weekdays, Enum.Parse(weekdays, s), "d"));

        Console.WriteLine();
        Console.WriteLine("Enums can also be created which have values that represent some meaningful amount.");
        Console.WriteLine("The BoilingPoints Enum defines the following items, and corresponding values:");

        foreach ( string s in Enum.GetNames(boiling) )
            Console.WriteLine( "{0,-11}= {1}", s, Enum.Format(boiling, Enum.Parse(boiling, s), "d"));

        Colors myColors = Colors.Red | Colors.Blue | Colors.Yellow;
        Console.WriteLine();
        Console.WriteLine("myColors holds a combination of colors. Namely: {0}", myColors);
    }
}
open System

type Days =
    | Saturday = 0
    | Sunday = 1
    | Monday = 2
    | Tuesday = 3
    | Wednesday = 4
    | Thursday = 5
    | Friday = 6

type BoilingPoints =
    | Celsius = 100
    | Fahrenheit = 212

[<Flags>]
type Colors =
    | Red = 1
    | Green = 2
    | Blue = 4
    | Yellow = 8

let weekdays = typeof<Days>
let boiling = typeof<BoilingPoints>

printfn "The days of the week, and their corresponding values in the Days Enum are:"

for s in Enum.GetNames weekdays do
    printfn $"""{s,-11}= {Enum.Format(weekdays, Enum.Parse(weekdays, s), "d")}"""

printfn "\nEnums can also be created which have values that represent some meaningful amount."
printfn "The BoilingPoints Enum defines the following items, and corresponding values:"

for s in Enum.GetNames boiling do
    printfn $"""{s,-11}= {Enum.Format(boiling, Enum.Parse(boiling, s), "d")}"""

let myColors = Colors.Red ||| Colors.Blue ||| Colors.Yellow
printfn $"\nmyColors holds a combination of colors. Namely: {myColors}"
Public Class EnumTest
    Enum Days
        Saturday
        Sunday
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
    End Enum 
    
    Enum BoilingPoints
        Celsius = 100
        Fahrenheit = 212
    End Enum 
    
    <Flags()> _
    Enum Colors
        Red = 1
        Green = 2
        Blue = 4
        Yellow = 8
    End Enum 

    Public Shared Sub Main()
        Dim weekdays As Type = GetType(Days)
        Dim boiling As Type = GetType(BoilingPoints)

        Console.WriteLine("The days of the week, and their corresponding values in the Days Enum are:")

        Dim s As String
        For Each s In  [Enum].GetNames(weekdays)
            Console.WriteLine("{0,-11} = {1}", s, [Enum].Format(weekdays, [Enum].Parse(weekdays, s), "d"))
        
        Next s
        Console.WriteLine()
        Console.WriteLine("Enums can also be created which have values that represent some meaningful amount.")
        Console.WriteLine("The BoilingPoints Enum defines the following items, and corresponding values:")

        For Each s In  [Enum].GetNames(boiling)
            Console.WriteLine("{0,-11} = {1}", s, [Enum].Format(boiling, [Enum].Parse(boiling, s), "d"))
        Next s

        Dim myColors As Colors = Colors.Red Or Colors.Blue Or Colors.Yellow
        Console.WriteLine()
        Console.WriteLine("myColors holds a combination of colors. Namely: {0}", myColors)
    End Sub 
End Class