Enum 클래스

정의

열거형에 대한 기본 클래스를 제공합니다.

public ref class Enum abstract : ValueType, IComparable, IConvertible, IFormattable
public ref class Enum abstract : ValueType, IComparable, IConvertible, ISpanFormattable
public ref class Enum abstract : ValueType, IComparable, IFormattable
public abstract class Enum : ValueType, IComparable, IConvertible, IFormattable
public abstract class Enum : ValueType, IComparable, IConvertible, ISpanFormattable
[System.Serializable]
public abstract class Enum : ValueType, IComparable, IConvertible, IFormattable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Enum : ValueType, IComparable, IConvertible, IFormattable
public abstract class Enum : ValueType, IComparable, IFormattable
type Enum = class
    inherit ValueType
    interface IComparable
    interface IConvertible
    interface IFormattable
type Enum = class
    inherit ValueType
    interface IComparable
    interface IConvertible
    interface ISpanFormattable
    interface IFormattable
[<System.Serializable>]
type Enum = class
    inherit ValueType
    interface IComparable
    interface IFormattable
    interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Enum = class
    inherit ValueType
    interface IComparable
    interface IFormattable
    interface IConvertible
type Enum = class
    inherit ValueType
    interface IComparable
    interface IFormattable
Public MustInherit Class Enum
Inherits ValueType
Implements IComparable, IConvertible, IFormattable
Public MustInherit Class Enum
Inherits ValueType
Implements IComparable, IConvertible, ISpanFormattable
Public MustInherit Class Enum
Inherits ValueType
Implements IComparable, IFormattable
상속
파생
특성
구현

예제

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

using namespace System;
enum class Days
{
   Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
};

enum class BoilingPoints
{
   Celsius = 100,
   Fahrenheit = 212
};

[Flags]

enum class Colors
{
   Red = 1,
   Green = 2,
   Blue = 4,
   Yellow = 8
};

int main()
{
   Type^ weekdays = Days::typeid;
   Type^ boiling = BoilingPoints::typeid;
   Console::WriteLine(  "The days of the week, and their corresponding values in the Days Enum are:" );
   Array^ a = Enum::GetNames( weekdays );
   Int32 i = 0;
   do
   {
      Object^ o = a->GetValue( i );
      Console::WriteLine(  "{0,-11}= {1}", o->ToString(), Enum::Format( weekdays, Enum::Parse( weekdays, o->ToString() ),  "d" ) );
   }
   while ( ++i < a->Length );

   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:" );
   i = 0;
   Array^ b = Enum::GetNames( boiling );
   do
   {
      Object^ o = b->GetValue( i );
      Console::WriteLine(  "{0,-11}= {1}", o->ToString(), Enum::Format( boiling, Enum::Parse( boiling, o->ToString() ),  "d" ) );
   }
   while ( ++i < b->Length );

   Array^ c = Enum::GetNames( Colors::typeid );
   Colors myColors = Colors::Red | Colors::Blue | Colors::Yellow;
   Console::WriteLine();
   Console::Write(  "myColors holds a combination of colors. Namely:" );
   for ( i = 0; i < 3; i++ )
      Console::Write(  " {0}", c->GetValue( i ) );
}
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

설명

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

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

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

항목 내용

열거형 형식 인스턴스화 열거형 형식 만들기 모범 사례 열거을 사용하여 작업 수행 열거값 구문 분석 열거형 값 반복 열형 멤버비독점 멤버 및 Flags 특성열거형 메서드 추가

열거형 형식 만들기

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

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

경고

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

열거형 형식 인스턴스화

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

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 Example
   Public Sub Main()
      Dim status As ArrivalStatus = ArrivalStatus.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 ArrivalStatus = CType(1, ArrivalStatus)
    Console.WriteLine("Arrival Status: {0} ({0:D})", status2)
    ' The example displays the following output:
    '       Arrival Status: Early (1)
    
  • 암시적 매개 변수 없는 생성자를 호출합니다. 다음 예제와 같이 이 경우 열거형 instance 기본 값은 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 ArrivalStatus()
    Console.WriteLine("Arrival Status: {0} ({0:D})", status1)
    ' The example displays the following output:
    '        Arrival Status: OnTime (0)
    
  • 또는 TryParse 메서드를 Parse 호출하여 열거형에 상수의 이름이 포함된 문자열을 구문 분석합니다. 자세한 내용은 열거형 값 구문 분석 섹션을 참조하세요 .

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

열거형 모범 사례

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

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

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

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

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

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

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

열거형을 만들 때는 새 메서드를 정의할 수 없습니다. 그러나 열거형 형식은 클래스에서 정적 및 instance 메서드의 전체 집합을 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 ArrivalStatus = CType(value3, ArrivalStatus)

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 ArrivalStatus = CType(ArrivalStatus.ToObject(GetType(ArrivalStatus), number), ArrivalStatus)

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

using System;

public enum ArrivalStatus { Unknown=-3, Late=-1, OnTime=0, Early=1 };

public class Example
{
   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 ArrivalStatus As Integer
   Unknown = -3
   Late = -1
   OnTime = 0
   Early = 1
End Enum

Module Example
   Public Sub Main()
      Dim values() As Integer = { -3, -1, 0, 1, 5, Int32.MaxValue }
      For Each value In values
         Dim status As ArrivalStatus
         If [Enum].IsDefined(GetType(ArrivalStatus), value)
            status = CType(value, ArrivalStatus) 
         Else
            status = ArrivalStatus.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 명시적 인터페이스 구현을 제공하지만 와 같은 ToInt32클래스의 Convert 메서드를 사용하여 이러한 변환을 수행해야 합니다. 다음 예제에서는 메서드와 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 ArrivalStatus = ArrivalStatus.Early
Dim number = Convert.ChangeType(status, [Enum].GetUnderlyingType(GetType(ArrivalStatus)))
Console.WriteLine("Converted {0} to {1}", status, number)
' The example displays the following output:
'       Converted Early to 1

열거형 값 구문 분석

ParseTryParse 메서드를 사용하면 열거형 값의 문자열 표현을 해당 값으로 변환할 수 있습니다. 문자열 표현은 열거형 상수의 이름 또는 기본 값일 수 있습니다. 문자열을 열거형의 기본 형식 값으로 변환할 수 있는 경우 구문 분석 메서드는 특정 열거형의 멤버가 아닌 숫자의 문자열 표현을 성공적으로 변환합니다. 이를 방지하기 위해 메서드를 IsDefined 호출하여 구문 분석 메서드의 결과가 유효한 열거형 값인지 확인할 수 있습니다. 이 예제에서는 이 방법을 설명하고 및 Enum.TryParse<TEnum>(String, TEnum) 메서드에 대한 호출을 Parse(Type, String) 보여 줍니다. 제네릭이 아닌 구문 분석 메서드는 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 ArrivalStatus = CType([Enum].Parse(GetType(ArrivalStatus), number), ArrivalStatus)
   If Not [Enum].IsDefined(GetType(ArrivalStatus), status1) Then status1 = ArrivalStatus.Unknown
   Console.WriteLine("Converted '{0}' to {1}", number, status1)
Catch e As FormatException
   Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.", 
                     number)
End Try   
   
Dim status2 As ArrivalStatus
If [Enum].TryParse(Of ArrivalStatus)(name, status2) Then
   If Not [Enum].IsDefined(GetType(ArrivalStatus), status2) Then status2 = ArrivalStatus.Unknown
   Console.WriteLine("Converted '{0}' to {1}", name, status2)
Else
   Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.", 
                     number)
End If
' The example displays the following output:
'       Converted '-1' to Late
'       Converted 'Early' to Early

열거형 값 서식 지정

정적 Format 메서드와 instance 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 ArrivalStatus = ArrivalStatus.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 또는 인터페이스를 IEnumerable 구현하지 않습니다. 이 인터페이스를 사용하면 (C#의 경우), (F#) for..in 또는 For Each (Visual Basic의 경우) 구문을 사용하여 foreach 컬렉션의 멤버를 반복 IEnumerable<T> 할 수 있습니다. 그러나 두 가지 방법 중 하나로 멤버를 열거할 수 있습니다.

  • 메서드를 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(ArrivalStatus))
    Console.WriteLine("Members of {0}:", GetType(ArrivalStatus).Name)
    Array.Sort(names)
    For Each name In names
       Dim status As ArrivalStatus = CType([Enum].Parse(GetType(ArrivalStatus), name),
                                     ArrivalStatus)
       Console.WriteLine("   {0} ({0:D})", status)
    Next
    ' The example displays the following output:
    '       Members of ArrivalStatus:
    '          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(ArrivalStatus))
    Console.WriteLine("Members of {0}:", GetType(ArrivalStatus).Name)
    For Each value In values
       Dim status As ArrivalStatus = CType([Enum].ToObject(GetType(ArrivalStatus), value),
                                           ArrivalStatus)
       Console.WriteLine("   {0} ({0:D})", status)
    Next                                       
    ' The example displays the following output:
    '       Members of ArrivalStatus:
    '          OnTime (0)
    '          Early (1)
    '          Unknown (-3)
    '          Late (-1)
    

비독점 멤버 및 Flags 특성

열거형의 일반적인 용도 중 하나는 상호 배타적인 값 집합을 나타내는 것입니다. 예를 들어 ArrivalStatus instance , OnTime또는 LateEarly이 있을 수 있습니다. instance 값 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 등)로 정의합니다. 즉, 결합된 열거형 상수의 개별 플래그가 겹치지 않습니다.

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

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

  • 플래그가 숫자 값에 설정되어 있는지 여부를 테스트하는 편리한 방법은 다음 예제와 같이 instance 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)과 Enum 같은 enum 언어 구조에 의해 정의되므로 클래스에서 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 Example
{
  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.

생성자

Enum()

Enum 클래스의 새 인스턴스를 초기화합니다.

메서드

CompareTo(Object)

이 인스턴스를 지정된 개체와 비교하여 상대 값의 표시를 반환합니다.

Equals(Object)

이 인스턴스가 지정된 개체와 같은지를 나타내는 값을 반환합니다.

Format(Type, Object, String)

열거 형식이 지정된 특정 값을 특정 서식에 따라 해당 문자열 표현으로 변환합니다.

GetHashCode()

이 인스턴스의 값에 대한 해시 코드를 반환합니다.

GetName(Type, Object)

지정된 값의 특정 열거형에서 상수의 이름을 검색합니다.

GetName<TEnum>(TEnum)

지정된 값을 갖는 지정된 열거형 형식에서 상수의 이름을 검색합니다.

GetNames(Type)

지정된 열거형에서 상수 이름의 배열을 검색합니다.

GetNames<TEnum>()

지정된 열거형 형식에서 상수 이름의 배열을 검색합니다.

GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
GetTypeCode()

이 열거형 멤버에 대한 내부 형식의 형식 코드를 반환합니다.

GetUnderlyingType(Type)

지정된 열거형의 내부 형식을 반환합니다.

GetValues(Type)

지정된 열거형에서 상수 값의 배열을 검색합니다.

GetValues<TEnum>()

지정된 열거형 형식에서 상수 값의 배열을 검색합니다.

GetValuesAsUnderlyingType(Type)

지정된 열거형에서 기본 형식 상수 값의 배열을 검색합니다.

GetValuesAsUnderlyingType<TEnum>()

지정된 열거형 형식의 기본 형식 상수 값 배열을 검색합니다.

HasFlag(Enum)

현재 인스턴스에 하나 이상의 비트 필드가 설정되어 있는지를 확인합니다.

IsDefined(Type, Object)

지정된 정수 값 또는 문자열로 해당 이름이 지정된 열거형에 있는지 여부를 나타내는 부울을 반환합니다.

IsDefined<TEnum>(TEnum)

지정된 정수 값 또는 문자열로의 해당 이름이 지정된 열거형에 있는지 여부를 나타내는 부울을 반환합니다.

MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
Parse(Type, ReadOnlySpan<Char>)

하나 이상의 열거형 상수의 이름 또는 숫자 값에 대한 문자 표현 범위를 해당하는 열거형 개체로 변환합니다.

Parse(Type, ReadOnlySpan<Char>, Boolean)

하나 이상의 열거형 상수의 이름 또는 숫자 값에 대한 문자 표현 범위를 해당하는 열거형 개체로 변환합니다. 매개 변수는 연산이 대/소문자를 구분하지 않는지를 지정합니다.

Parse(Type, String)

하나 이상의 열거된 상수의 이름이나 숫자 값의 문자열 표현을 해당하는 열거형 개체로 변환합니다.

Parse(Type, String, Boolean)

하나 이상의 열거된 상수의 이름이나 숫자 값의 문자열 표현을 해당하는 열거형 개체로 변환합니다. 매개 변수는 연산이 대/소문자를 구분하지 않는지를 지정합니다.

Parse<TEnum>(ReadOnlySpan<Char>)

에 지정된 TEnum 하나 이상의 열거형 상수의 이름 또는 숫자 값의 문자 표현 범위를 해당하는 열거형 개체로 변환합니다.

Parse<TEnum>(ReadOnlySpan<Char>, Boolean)

에 지정된 TEnum 하나 이상의 열거형 상수의 이름 또는 숫자 값의 문자 표현 범위를 해당하는 열거형 개체로 변환합니다. 매개 변수는 연산이 대/소문자를 구분하지 않는지를 지정합니다.

Parse<TEnum>(String)

TEnum에 의해 하나 이상의 열거된 상수의 이름이나 숫자 값의 문자열 표현을 해당하는 열거형 개체로 변환합니다.

Parse<TEnum>(String, Boolean)

TEnum에 의해 하나 이상의 열거된 상수의 이름이나 숫자 값의 문자열 표현을 해당하는 열거형 개체로 변환합니다. 매개 변수는 연산이 대/소문자를 구분하지 않는지를 지정합니다.

ToObject(Type, Byte)

지정된 8비트 부호 없는 정수를 열거형 멤버로 변환합니다.

ToObject(Type, Int16)

지정된 16비트 부호 있는 정수를 열거형 멤버로 변환합니다.

ToObject(Type, Int32)

지정된 32비트 부호 있는 정수를 열거형 멤버로 변환합니다.

ToObject(Type, Int64)

지정된 64비트 부호 있는 정수를 열거형 멤버로 변환합니다.

ToObject(Type, Object)

정수 값이 있는 지정된 개체를 열거형 멤버로 변환합니다.

ToObject(Type, SByte)

지정된 8비트 부호 있는 정수 값을 열거형 멤버로 변환합니다.

ToObject(Type, UInt16)

지정된 16비트 부호 없는 정수 값을 열거형 멤버로 변환합니다.

ToObject(Type, UInt32)

지정된 32비트 부호 없는 정수 값을 열거형 멤버로 변환합니다.

ToObject(Type, UInt64)

지정된 64비트 부호 없는 정수 값을 열거형 멤버로 변환합니다.

ToString()

이 인스턴스의 값을 해당하는 문자열 표현으로 변환합니다.

ToString(IFormatProvider)
사용되지 않습니다.
사용되지 않습니다.

이 메서드 오버로드는 더 이상 사용되지 않으므로 ToString()을 사용합니다.

ToString(String)

지정된 형식을 사용하여 이 인스턴스의 값을 해당하는 문자열 표현으로 변환합니다.

ToString(String, IFormatProvider)
사용되지 않습니다.
사용되지 않습니다.

이 메서드 오버로드는 더 이상 사용되지 않으므로 ToString(String)을 사용합니다.

TryFormat<TEnum>(TEnum, Span<Char>, Int32, ReadOnlySpan<Char>)

instance 열거형 형식의 값을 제공된 문자 범위로 서식을 지정하려고 시도합니다.

TryParse(Type, ReadOnlySpan<Char>, Boolean, Object)

하나 이상의 열거형 상수의 이름 또는 숫자 값에 대한 문자 표현 범위를 해당하는 열거형 개체로 변환합니다. 매개 변수는 연산이 대/소문자를 구분하지 않는지를 지정합니다.

TryParse(Type, ReadOnlySpan<Char>, Object)

하나 이상의 열거형 상수의 이름 또는 숫자 값에 대한 문자 표현 범위를 해당하는 열거형 개체로 변환합니다.

TryParse(Type, String, Boolean, Object)

하나 이상의 열거된 상수의 이름이나 숫자 값의 문자열 표현을 해당하는 열거형 개체로 변환합니다.

TryParse(Type, String, Object)

하나 이상의 열거된 상수의 이름이나 숫자 값의 문자열 표현을 해당하는 열거형 개체로 변환합니다.

TryParse<TEnum>(ReadOnlySpan<Char>, Boolean, TEnum)

하나 이상의 열거된 상수의 이름이나 숫자 값의 문자열 표현을 해당하는 열거형 개체로 변환합니다. 매개 변수는 연산이 대/소문자를 구분하는지를 지정합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

TryParse<TEnum>(ReadOnlySpan<Char>, TEnum)

하나 이상의 열거된 상수의 이름이나 숫자 값의 문자열 표현을 해당하는 열거형 개체로 변환합니다.

TryParse<TEnum>(String, Boolean, TEnum)

하나 이상의 열거된 상수의 이름이나 숫자 값의 문자열 표현을 해당하는 열거형 개체로 변환합니다. 매개 변수는 연산이 대/소문자를 구분하는지를 지정합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

TryParse<TEnum>(String, TEnum)

하나 이상의 열거된 상수의 이름이나 숫자 값의 문자열 표현을 해당하는 열거형 개체로 변환합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

명시적 인터페이스 구현

IConvertible.GetTypeCode()

Enum 인스턴스의 해시 코드를 반환합니다.

IConvertible.ToBoolean(IFormatProvider)

현재 값을 내부 형식에 따라 부울 값으로 변환합니다.

IConvertible.ToByte(IFormatProvider)

현재 값을 내부 형식에 따라 8비트 부호 없는 정수로 변환합니다.

IConvertible.ToChar(IFormatProvider)

현재 값을 내부 형식에 따라 유니코드 문자로 변환합니다.

IConvertible.ToDateTime(IFormatProvider)

현재 값을 내부 형식에 따라 DateTime로 변환합니다.

IConvertible.ToDecimal(IFormatProvider)

현재 값을 내부 형식에 따라 Decimal로 변환합니다.

IConvertible.ToDouble(IFormatProvider)

현재 값을 내부 형식에 따라 배정밀도 부동 소수점 숫자로 변환합니다.

IConvertible.ToInt16(IFormatProvider)

현재 값을 내부 형식에 따라 16비트 부호 있는 정수로 변환합니다.

IConvertible.ToInt32(IFormatProvider)

현재 값을 내부 형식에 따라 32비트 부호 있는 정수로 변환합니다.

IConvertible.ToInt64(IFormatProvider)

현재 값을 내부 형식에 따라 64비트 부호 있는 정수로 변환합니다.

IConvertible.ToSByte(IFormatProvider)

현재 값을 내부 형식에 따라 8비트 부호 있는 정수로 변환합니다.

IConvertible.ToSingle(IFormatProvider)

현재 값을 내부 형식에 따라 단정밀도 부동 소수점 숫자로 변환합니다.

IConvertible.ToString(IFormatProvider)
사용되지 않습니다.

이 메서드 오버로드는 더 이상 사용되지 않으므로 대신 ToString()을 사용합니다.

IConvertible.ToType(Type, IFormatProvider)

현재 값을 내부 형식에 따라 지정된 형식으로 변환합니다.

IConvertible.ToUInt16(IFormatProvider)

현재 값을 내부 형식에 따라 16비트 부호 없는 정수로 변환합니다.

IConvertible.ToUInt32(IFormatProvider)

현재 값을 내부 형식에 따라 32비트 부호 없는 정수로 변환합니다.

IConvertible.ToUInt64(IFormatProvider)

현재 값을 내부 형식에 따라 64비트 부호 없는 정수로 변환합니다.

IFormattable.ToString(String, IFormatProvider)
사용되지 않습니다.

이 메서드 오버로드는 더 이상 사용되지 않으므로 ToString(String)을 사용합니다.

ISpanFormattable.TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)

열거형 값의 형식을 제공된 문자 범위로 지정하려고 시도합니다.

적용 대상

스레드 보안

이 형식은 스레드로부터 안전합니다.

추가 정보