이 플래그를 사용하면 열거형 데이터는 bit field로 처리할수 있습니다.
열거형 상수는 일반적으로 상호배타적인 요소로 사용되고,
bit fileld 는 bit 조합으로 처리해야 할 경우에 사용됩니다.

bit field는 정해지지 않은 값을 OR 연산으로 새롭게 만들수 있으나 열거형 상수는 그렇게 할수 없다.
많은 언어에서 열거형상수보다 bit field가 다양하게 사용됩니다.


FlagAttribute 와 Enum 사용지침
 - AND, OR, EXCLUSIVE OR 의 비트 연산을 필요한 경우에는 FlagAttribute 를 선언해야 합니다.
 - 2의 배수로 정의 합니다. 즉, 1, 2, 4, 8, 16 형태로 개별 플래그(비트)가 겹치기 않게 해야 합니다.

아래 예제의 결과를 보면 의미를 정확히 알수 있을 겁니다.

예제
 // 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
*/


'스터디 > C#.NET:자료' 카테고리의 다른 글

런타임에러, 예외 처리 방법, try catch  (0) 2010.10.31
ListView 에 ComboBox 붙이기  (3) 2010.10.28
C# 에서 string 관련  (0) 2010.10.22
TreeView 이용하기  (1) 2010.10.18
프로그램을 트레이 아이콘으로 보내기  (0) 2010.10.11
레지스트리 변경 이벤트  (0) 2010.10.08
GC.SuppressFinalize 메서드  (0) 2010.10.08
클래스 내에서의 쓰레드  (0) 2010.10.08
unchecked 키워드  (0) 2010.10.07
C# 마우스 커서 모양  (0) 2010.10.05

+ Recent posts