System.FlagsAttribute Class

public class FlagsAttribute : Attribute

Base Types

Object
Attribute
FlagsAttribute

Assembly

mscorlib

Library

BCL

Summary

Indicates that the Enum targeted by the current attribute is declared as a bit-field.

Description

The FlagsAttribute class provides the consumer of a Enum the information that the enumeration is to be used as a bit-field. Additionally, when formatting a Enum, using the FlagsAttribute causes a value that is a bitwise OR combination of multiple fields to print correctly.

[Note: Bit-fields are generally used for lists of elements that might occur in combination; whereas enumeration constants are generally used for lists of mutually exclusive elements. Therefore, bit-fields are designed to be combined with the bitwise OR operator to generate unnamed values, whereas enumerated constants are not. Languages vary in their usage of bit-fields compared to enumeration constants.

This attribute can only be applied to enumerations.

]

Example

The following example demonstrates the use of FlagsAttribute on the formatting of a Enum. With this attribute, the Position enumeration is used as a bit-field, and the value 3 (Top | Left) is considered a valid value for the enumeration when formatting. Without this attribute, the enumeration Color is not used as a bit-field, and the value 3 (Red | Blue) is not considered a valid value for the enumeration when formatting.

using System;
[FlagsAttribute()] 
public enum Position { 
 Top = 0x1, 
 Left = 0x2, 
 Bottom = 0x4, 
 Right = 0x8 
} 
//enum Color declared without FlagsAttribute 
public enum Color { 
 Red = 0x1, 
 Blue = 0x2, 
 Yellow = 0x4 
} 
public class enumFormat { 
 public static void Main() { 
 Position p = Position.Top | Position.Left; 
 Console.WriteLine("Position: {0}", p); 
 Color c = Color.Red | Color.Blue; 
 Console.WriteLine("Color: {0}", c); 
 } 
} 
 
The output is

Position: Top, Left

Color: 3

Attributes

AttributeUsageAttribute(AttributeTargets.Enum, AllowMultiple=false, Inherited=false)

See Also

System Namespace

Members

FlagsAttribute Constructors

FlagsAttribute Constructor


FlagsAttribute Constructor

public FlagsAttribute();

Summary

Constructs a new instance of the FlagsAttribute class.

See Also

System.FlagsAttribute Class, System Namespace

AltStyle によって変換されたページ (->オリジナル) /