이 플래그를 사용하면 열거형 데이터는 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
*/
- [2018/02/26] List 에서 고유값 얻기 ()
- [2015/05/22] C#, 아두이노 간의 WIFI 통신으로 LCD 제어 (4566)
- [2015/03/13] 항상 마지막에 추가한 TEXT 보이게 ()
- [2014/01/17] ComboBox Text 편집 안되게 (14491)
- [2014/01/08] if 문에서 여러개 비교할때 (25340) *3
- [2013/12/30] C++, C# 간단한 기능 비교 (12884)
- [2013/12/18] 3자리마다 ,(콤마) 찍기 (원화, 달러 표시) (15224)
- [2013/09/29] 설치된 IE 버전 얻기 (12398)
- [2013/08/29] byte array to Hexa String (13026)
- [2013/06/25] string array to string (스트링 문자열 합치기) (23713)