다음을 통해 공유


FlagsAttribute 클래스

열거형을 비트 필드 즉, 플래그 집합으로 처리할 수 있음을 나타냅니다.

네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<SerializableAttribute> _
<AttributeUsageAttribute(AttributeTargets.Enum, Inherited:=False)> _
<ComVisibleAttribute(True)> _
Public Class FlagsAttribute
    Inherits Attribute
‘사용 방법
Dim instance As FlagsAttribute
[SerializableAttribute] 
[AttributeUsageAttribute(AttributeTargets.Enum, Inherited=false)] 
[ComVisibleAttribute(true)] 
public class FlagsAttribute : Attribute
[SerializableAttribute] 
[AttributeUsageAttribute(AttributeTargets::Enum, Inherited=false)] 
[ComVisibleAttribute(true)] 
public ref class FlagsAttribute : public Attribute
/** @attribute SerializableAttribute() */ 
/** @attribute AttributeUsageAttribute(AttributeTargets.Enum, Inherited=false) */ 
/** @attribute ComVisibleAttribute(true) */ 
public class FlagsAttribute extends Attribute
SerializableAttribute 
AttributeUsageAttribute(AttributeTargets.Enum, Inherited=false) 
ComVisibleAttribute(true) 
public class FlagsAttribute extends Attribute

설명

일반적으로 비트 필드는 결합을 통해 생성되는 요소 목록에 사용되지만 열거형 상수는 함께 사용할 수 없는 요소 목록에 사용됩니다. 따라서 비트 필드는 비트 OR 연산으로 결합시켜 명명되지 않은 값을 생성할 수 있지만 열거 상수는 그렇지 않습니다. 비트 필드와 열거형 상수에서 언어가 다르게 사용됩니다.

FlagsAttribute의 특성

AttributeUsageAttribute는 이 클래스에 적용되며, 해당 Inherited 속성은 false를 지정합니다. 이 특성은 열거형에만 적용할 수 있습니다.

FlagsAttribute 및 열거형 지침

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

  • 열거형 상수를 2의 거듭제곱(즉, 1, 2, 4, 8 등)으로 정의합니다. 이렇게 하면 조합된 열거형 상수의 개별 플래그가 겹치지 않게 됩니다.

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

  • 여러 플래그 위치가 1로 설정될 수 있으므로 음수를 플래그 열거형 상수로 정의할 때는 주의해야 합니다. 코드가 혼동스러워지고 코딩 오류가 발생할 수 있습니다.

  • 숫자 값에 플래그가 설정되어 있는지 여부를 테스트하는 편리한 방법은 숫자 값과 플래그 열거형 상수 간에 비트 AND 연산을 수행하여 숫자 값에서 플래그에 해당하지 않는 모든 비트를 0으로 설정한 다음 해당 연산의 결과가 플래그 열거형 상수와 같은지 여부를 테스트하는 것입니다.

  • 값이 0인 플래그 열거형 상수의 이름으로 None을 사용합니다. 플래그를 테스트할 때는 비트 AND 연산에 None 열거형 상수를 사용할 수 없습니다. 결과가 항상 0이 되기 때문입니다. 그러나 숫자 값과 None 열거형 상수 간에 비트 비교가 아닌 논리 비교를 수행하여 숫자 값의 모든 비트가 설정되었는지 여부를 확인할 수 있습니다.

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

    응용 프로그램에서 나타내야 하는 명확한 기본 경우가 있으면 값이 0인 열거형 상수를 사용하여 기본값을 나타내는 것이 좋습니다. 기본 경우가 없으면 다른 열거형 상수가 나타내지 않는 경우를 의미하는 0을 값으로 갖는 열거형 상수를 사용하는 것이 좋습니다.

  • 단지 열거형 자체의 상태를 미러링하기 위해 열거형 값을 정의하지 마십시오. 예를 들어, 단지 열거형의 끝을 표시하는 열거형 상수를 정의하지 마십시오. 열거형의 마지막 값을 확인할 경우에는 해당 값을 명시적으로 확인해야 합니다. 또한 범위 내의 모든 값이 유효한 경우 첫 번째 열거형 상수와 마지막 열거형 상수의 범위를 확인할 수 있습니다.

  • 나중에 사용하기 위해 예약된 열거형 상수는 지정하지 마십시오.

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

예제

다음 코드 예제에서는 FlagsAttribute 특성의 사용 방법을 보여 주고 Enum 선언에 FlagsAttribute를 사용할 경우 ToString 메서드에 미치는 효과를 보여 줍니다.

' Example of the FlagsAttribute attribute.
Imports System
Imports Microsoft.VisualBasic

Module FlagsAttributeDemo
    
    ' Define an Enum without FlagsAttribute.
    Enum SingleHue as Short
        Black = 0
        Red = 1
        Green = 2
        Blue = 4
    End Enum

    ' Define an Enum with FlagsAttribute.
    <FlagsAttribute( )> _
    Enum MultiHue as Short
        Black = 0
        Red = 1
        Green = 2
        Blue = 4
    End Enum

    Sub Main( )
        Console.WriteLine( _
            "This example of the FlagsAttribute attribute " & _
            vbCrLf & "generates the following output." )
        Console.WriteLine( vbCrLf & _
            "All possible combinations of values of an " & _
            vbCrLf & "Enum without FlagsAttribute:" & vbCrLf )
        
        ' Display all possible combinations of values.
        Dim val as Integer
        For val = 0 to 8
            Console.WriteLine( "{0,3} - {1}", _
                val, CType( val, SingleHue ).ToString( ) )
        Next val

        Console.WriteLine( vbCrLf & _
            "All possible combinations of values of an " & _
            vbCrLf & "Enum with FlagsAttribute:" & vbCrLf )
        
        ' Display all possible combinations of values.
        ' Also display an invalid value.
        For val = 0 to 8
            Console.WriteLine( "{0,3} - {1}", _
                val, CType( val, MultiHue ).ToString( ) )
        Next val
    End Sub 
End Module 

' This example of the FlagsAttribute attribute
' generates the following output.
' 
' All possible combinations of values of an
' Enum without FlagsAttribute:
' 
'   0 - Black
'   1 - Red
'   2 - Green
'   3 - 3
'   4 - Blue
'   5 - 5
'   6 - 6
'   7 - 7
'   8 - 8
' 
' All possible combinations of values of an
' Enum with FlagsAttribute:
' 
'   0 - Black
'   1 - Red
'   2 - Green
'   3 - Red, Green
'   4 - Blue
'   5 - Red, Blue
'   6 - Green, Blue
'   7 - Red, Green, Blue
'   8 - 8
// Example of the FlagsAttribute attribute.
using System;

class FlagsAttributeDemo
{
    // Define an Enum without FlagsAttribute.
    enum SingleHue : short
    {
        Black = 0,
        Red = 1,
        Green = 2,
        Blue = 4
    };

    // Define an Enum with FlagsAttribute.
    [FlagsAttribute] 
    enum MultiHue : short
    {
        Black = 0,
        Red = 1,
        Green = 2,
        Blue = 4
    };

    static void Main( )
    {
        Console.WriteLine( 
            "This example of the FlagsAttribute attribute \n" +
            "generates the following output." );
        Console.WriteLine( 
            "\nAll possible combinations of values of an \n" +
            "Enum without FlagsAttribute:\n" );
        
        // Display all possible combinations of values.
        for( int val = 0; val <= 8; val++ )
            Console.WriteLine( "{0,3} - {1}", 
                val, ( (SingleHue)val ).ToString( ) );

        Console.WriteLine( 
            "\nAll possible combinations of values of an \n" +
            "Enum with FlagsAttribute:\n" );
        
        // Display all possible combinations of values.
        // Also display an invalid value.
        for( int val = 0; val <= 8; val++ )
            Console.WriteLine( "{0,3} - {1}", 
                val, ( (MultiHue)val ).ToString( ) );
    } 
} 

/*
This example of the FlagsAttribute attribute
generates the following output.

All possible combinations of values of an
Enum without FlagsAttribute:

  0 - Black
  1 - Red
  2 - Green
  3 - 3
  4 - Blue
  5 - 5
  6 - 6
  7 - 7
  8 - 8

All possible combinations of values of an
Enum with FlagsAttribute:

  0 - Black
  1 - Red
  2 - Green
  3 - Red, Green
  4 - Blue
  5 - Red, Blue
  6 - Green, Blue
  7 - Red, Green, Blue
  8 - 8
*/
// Example of the FlagsAttribute attribute.
using namespace System;

// Define an Enum without FlagsAttribute.
enum class SingleHue : short
{
   Black = 0,
   Red = 1,
   Green = 2,
   Blue = 4
};


// Define an Enum with FlagsAttribute.

[FlagsAttribute]
enum class MultiHue : short
{
   Black = 0,
   Red = 1,
   Green = 2,
   Blue = 4
};

int main()
{
   Console::WriteLine( "This example of the FlagsAttribute attribute \n"
   "generates the following output." );
   Console::WriteLine( "\nAll possible combinations of values of an \n"
   "Enum without FlagsAttribute:\n" );
   
   // Display all possible combinations of values.
   for ( int val = 0; val <= 8; val++ )
      Console::WriteLine( "{0,3} - {1}", val, ((SingleHue)val).ToString() );
   Console::WriteLine( "\nAll possible combinations of values of an \n"
   "Enum with FlagsAttribute:\n" );
   
   // Display all possible combinations of values.
   // Also display an invalid value.
   for ( int val = 0; val <= 8; val++ )
      Console::WriteLine( "{0,3} - {1}", val, ((MultiHue)val).ToString() );
}

/*
This example of the FlagsAttribute attribute
generates the following output.

All possible combinations of values of an
Enum without FlagsAttribute:

  0 - Black
  1 - Red
  2 - Green
  3 - 3
  4 - Blue
  5 - 5
  6 - 6
  7 - 7
  8 - 8

All possible combinations of values of an
Enum with FlagsAttribute:

  0 - Black
  1 - Red
  2 - Green
  3 - Red, Green
  4 - Blue
  5 - Red, Blue
  6 - Green, Blue
  7 - Red, Green, Blue
  8 - 8
*/

상속 계층 구조

System.Object
   System.Attribute
    System.FlagsAttribute

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

FlagsAttribute 멤버
System 네임스페이스