FlagsAttribute Třída
Definice
Označuje, že výčet lze považovat za bitové pole; To znamená sada příznaků.Indicates that an enumeration can be treated as a bit field; that is, a set of flags.
public ref class FlagsAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Enum, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class FlagsAttribute : Attribute
type FlagsAttribute = class
inherit Attribute
Public Class FlagsAttribute
Inherits Attribute
- Dědičnost
- Atributy
Příklady
FlagsAttribute
Následující příklad ilustruje použití atributu a ukazuje vliv ToString na Enum metodu použití FlagsAttribute
v deklaraci.The following example illustrates the use of the FlagsAttribute
attribute and shows the effect on the ToString method of using FlagsAttribute
on an Enum declaration.
using namespace System;
// Define an Enum without FlagsAttribute.
public enum class SingleHue : short
{
None = 0,
Black = 1,
Red = 2,
Green = 4,
Blue = 8
};
// Define an Enum with FlagsAttribute.
[Flags]
enum class MultiHue : short
{
None = 0,
Black = 1,
Red = 2,
Green = 4,
Blue = 8
};
int main()
{
// Display all possible combinations of values.
Console::WriteLine(
"All possible combinations of values without FlagsAttribute:");
for (int val = 0; val <= 16; val++)
Console::WriteLine("{0,3} - {1:G}", val, (SingleHue)val);
Console::WriteLine(
"\nAll possible combinations of values with FlagsAttribute:");
// Display all combinations of values, and invalid values.
for (int val = 0; val <= 16; val++ )
Console::WriteLine("{0,3} - {1:G}", val, (MultiHue)val);
}
// The example displays the following output:
// All possible combinations of values without FlagsAttribute:
// 0 - None
// 1 - Black
// 2 - Red
// 3 - 3
// 4 - Green
// 5 - 5
// 6 - 6
// 7 - 7
// 8 - Blue
// 9 - 9
// 10 - 10
// 11 - 11
// 12 - 12
// 13 - 13
// 14 - 14
// 15 - 15
// 16 - 16
//
// All possible combinations of values with FlagsAttribute:
// 0 - None
// 1 - Black
// 2 - Red
// 3 - Black, Red
// 4 - Green
// 5 - Black, Green
// 6 - Red, Green
// 7 - Black, Red, Green
// 8 - Blue
// 9 - Black, Blue
// 10 - Red, Blue
// 11 - Black, Red, Blue
// 12 - Green, Blue
// 13 - Black, Green, Blue
// 14 - Red, Green, Blue
// 15 - Black, Red, Green, Blue
// 16 - 16
using System;
class Example
{
// Define an Enum without FlagsAttribute.
enum SingleHue : short
{
None = 0,
Black = 1,
Red = 2,
Green = 4,
Blue = 8
};
// Define an Enum with FlagsAttribute.
[Flags]
enum MultiHue : short
{
None = 0,
Black = 1,
Red = 2,
Green = 4,
Blue = 8
};
static void Main( )
{
// Display all possible combinations of values.
Console.WriteLine(
"All possible combinations of values without FlagsAttribute:");
for(int val = 0; val <= 16; val++ )
Console.WriteLine( "{0,3} - {1:G}", val, (SingleHue)val);
// Display all combinations of values, and invalid values.
Console.WriteLine(
"\nAll possible combinations of values with FlagsAttribute:");
for( int val = 0; val <= 16; val++ )
Console.WriteLine( "{0,3} - {1:G}", val, (MultiHue)val);
}
}
// The example displays the following output:
// All possible combinations of values without FlagsAttribute:
// 0 - None
// 1 - Black
// 2 - Red
// 3 - 3
// 4 - Green
// 5 - 5
// 6 - 6
// 7 - 7
// 8 - Blue
// 9 - 9
// 10 - 10
// 11 - 11
// 12 - 12
// 13 - 13
// 14 - 14
// 15 - 15
// 16 - 16
//
// All possible combinations of values with FlagsAttribute:
// 0 - None
// 1 - Black
// 2 - Red
// 3 - Black, Red
// 4 - Green
// 5 - Black, Green
// 6 - Red, Green
// 7 - Black, Red, Green
// 8 - Blue
// 9 - Black, Blue
// 10 - Red, Blue
// 11 - Black, Red, Blue
// 12 - Green, Blue
// 13 - Black, Green, Blue
// 14 - Red, Green, Blue
// 15 - Black, Red, Green, Blue
// 16 - 16
Module Example
' Define an Enum without FlagsAttribute.
Enum SingleHue As Short
None = 0
Black = 1
Red = 2
Green = 4
Blue = 8
End Enum
' Define an Enum with FlagsAttribute.
<Flags()>
Enum MultiHue As Short
None = 0
Black = 1
Red = 2
Green = 4
Blue = 8
End Enum
Sub Main()
' Display all possible combinations of values.
Console.WriteLine(
"All possible combinations of values without FlagsAttribute:")
For val As Integer = 0 To 16
Console.WriteLine("{0,3} - {1:G}", val, CType(val, SingleHue))
Next
Console.WriteLine()
' Display all combinations of values, and invalid values.
Console.WriteLine(
"All possible combinations of values with FlagsAttribute:")
For val As Integer = 0 To 16
Console.WriteLine( "{0,3} - {1:G}", val, CType(val, MultiHue))
Next
End Sub
End Module
' The example displays the following output:
' All possible combinations of values without FlagsAttribute:
' 0 - None
' 1 - Black
' 2 - Red
' 3 - 3
' 4 - Green
' 5 - 5
' 6 - 6
' 7 - 7
' 8 - Blue
' 9 - 9
' 10 - 10
' 11 - 11
' 12 - 12
' 13 - 13
' 14 - 14
' 15 - 15
' 16 - 16
'
' All possible combinations of values with FlagsAttribute:
' 0 - None
' 1 - Black
' 2 - Red
' 3 - Black, Red
' 4 - Green
' 5 - Black, Green
' 6 - Red, Green
' 7 - Black, Red, Green
' 8 - Blue
' 9 - Black, Blue
' 10 - Red, Blue
' 11 - Black, Red, Blue
' 12 - Green, Blue
' 13 - Black, Green, Blue
' 14 - Red, Green, Blue
' 15 - Black, Red, Green, Blue
' 16 - 16
Následující příklad definuje dva výčty související se SingleHue
barvami a. MultiHue
The following example defines two color-related enumerations, SingleHue
and MultiHue
. Druhá má FlagsAttribute
atribut; předchozí není.The latter has the FlagsAttribute
attribute; the former does not. Příklad ukazuje rozdíl v chování v případě, že rozsah celých čísel, včetně celých čísel, která nepředstavují základní hodnoty výčtového typu, je převeden na typ výčtu a zobrazená reprezentace řetězce.The example shows the difference in behavior when a range of integers, including integers that do not represent underlying values of the enumeration type, are cast to the enumeration type and their string representations displayed. Například Všimněte si, že 3 nemůže být reprezentované jako SingleHue
hodnota, protože 3 není podkladová hodnota žádného SingleHue
člena, zatímco FlagsAttribute
atribut MultiHue
umožňuje reprezentovat 3 jako hodnotu Black, Red
.For example, note that 3 cannot be represented as a SingleHue
value because 3 is not the underlying value of any SingleHue
member, whereas the FlagsAttribute
attribute makes it possible to represent 3 as a MultiHue
value of Black, Red
.
using namespace System;
[Flags] enum class PhoneService
{
None = 0,
LandLine = 1,
Cell = 2,
Fax = 4,
Internet = 8,
Other = 16
};
void main()
{
// Define three variables representing the types of phone service
// in three households.
PhoneService household1 = PhoneService::LandLine | PhoneService::Cell |
PhoneService::Internet;
PhoneService household2 = PhoneService::None;
PhoneService household3 = PhoneService::Cell | PhoneService::Internet;
// Store the variables in an array for ease of access.
array<PhoneService>^ households = { household1, household2, household3 };
// Which households have no service?
for (int ctr = 0; ctr < households->Length; ctr++)
Console::WriteLine("Household {0} has phone service: {1}",
ctr + 1,
households[ctr] == PhoneService::None ?
"No" : "Yes");
Console::WriteLine();
// Which households have cell phone service?
for (int ctr = 0; ctr < households->Length; ctr++)
Console::WriteLine("Household {0} has cell phone service: {1}",
ctr + 1,
(households[ctr] & PhoneService::Cell) == PhoneService::Cell ?
"Yes" : "No");
Console::WriteLine();
// Which households have cell phones and land lines?
PhoneService cellAndLand = PhoneService::Cell | PhoneService::LandLine;
for (int ctr = 0; ctr < households->Length; ctr++)
Console::WriteLine("Household {0} has cell and land line service: {1}",
ctr + 1,
(households[ctr] & cellAndLand) == cellAndLand ?
"Yes" : "No");
Console::WriteLine();
// List all types of service of each household?//
for (int ctr = 0; ctr < households->Length; ctr++)
Console::WriteLine("Household {0} has: {1:G}",
ctr + 1, households[ctr]);
Console::WriteLine();
}
// The example displays the following output:
// Household 1 has phone service: Yes
// Household 2 has phone service: No
// Household 3 has phone service: Yes
//
// Household 1 has cell phone service: Yes
// Household 2 has cell phone service: No
// Household 3 has cell phone service: Yes
//
// Household 1 has cell and land line service: Yes
// Household 2 has cell and land line service: No
// Household 3 has cell and land line service: No
//
// Household 1 has: LandLine, Cell, Internet
// Household 2 has: None
// Household 3 has: Cell, Internet
using System;
[Flags] public enum PhoneService
{
None = 0,
LandLine = 1,
Cell = 2,
Fax = 4,
Internet = 8,
Other = 16
}
public class Example
{
public static void Main()
{
// Define three variables representing the types of phone service
// in three households.
var household1 = PhoneService.LandLine | PhoneService.Cell |
PhoneService.Internet;
var household2 = PhoneService.None;
var household3 = PhoneService.Cell | PhoneService.Internet;
// Store the variables in an array for ease of access.
PhoneService[] households = { household1, household2, household3 };
// Which households have no service?
for (int ctr = 0; ctr < households.Length; ctr++)
Console.WriteLine("Household {0} has phone service: {1}",
ctr + 1,
households[ctr] == PhoneService.None ?
"No" : "Yes");
Console.WriteLine();
// Which households have cell phone service?
for (int ctr = 0; ctr < households.Length; ctr++)
Console.WriteLine("Household {0} has cell phone service: {1}",
ctr + 1,
(households[ctr] & PhoneService.Cell) == PhoneService.Cell ?
"Yes" : "No");
Console.WriteLine();
// Which households have cell phones and land lines?
var cellAndLand = PhoneService.Cell | PhoneService.LandLine;
for (int ctr = 0; ctr < households.Length; ctr++)
Console.WriteLine("Household {0} has cell and land line service: {1}",
ctr + 1,
(households[ctr] & cellAndLand) == cellAndLand ?
"Yes" : "No");
Console.WriteLine();
// List all types of service of each household?//
for (int ctr = 0; ctr < households.Length; ctr++)
Console.WriteLine("Household {0} has: {1:G}",
ctr + 1, households[ctr]);
Console.WriteLine();
}
}
// The example displays the following output:
// Household 1 has phone service: Yes
// Household 2 has phone service: No
// Household 3 has phone service: Yes
//
// Household 1 has cell phone service: Yes
// Household 2 has cell phone service: No
// Household 3 has cell phone service: Yes
//
// Household 1 has cell and land line service: Yes
// Household 2 has cell and land line service: No
// Household 3 has cell and land line service: No
//
// Household 1 has: LandLine, Cell, Internet
// Household 2 has: None
// Household 3 has: Cell, Internet
<Flags()> Public Enum PhoneService As Integer
None = 0
LandLine = 1
Cell = 2
Fax = 4
Internet = 8
Other = 16
End Enum
Module Example
Public Sub Main()
' Define three variables representing the types of phone service
' in three households.
Dim household1 As PhoneService = PhoneService.LandLine Or
PhoneService.Cell Or
PhoneService.Internet
Dim household2 As PhoneService = PhoneService.None
Dim household3 As PhoneService = PhoneService.Cell Or
PhoneService.Internet
' Store the variables in an array for ease of access.
Dim households() As PhoneService = { household1, household2,
household3 }
' Which households have no service?
For ctr As Integer = 0 To households.Length - 1
Console.WriteLine("Household {0} has phone service: {1}",
ctr + 1,
If(households(ctr) = PhoneService.None,
"No", "Yes"))
Next
Console.WriteLine()
' Which households have cell phone service?
For ctr As Integer = 0 To households.Length - 1
Console.WriteLine("Household {0} has cell phone service: {1}",
ctr + 1,
If((households(ctr) And PhoneService.Cell) = PhoneService.Cell,
"Yes", "No"))
Next
Console.WriteLine()
' Which households have cell phones and land lines?
Dim cellAndLand As PhoneService = PhoneService.Cell Or PhoneService.LandLine
For ctr As Integer = 0 To households.Length - 1
Console.WriteLine("Household {0} has cell and land line service: {1}",
ctr + 1,
If((households(ctr) And cellAndLand) = cellAndLand,
"Yes", "No"))
Next
Console.WriteLine()
' List all types of service of each household?'
For ctr As Integer = 0 To households.Length - 1
Console.WriteLine("Household {0} has: {1:G}",
ctr + 1, households(ctr))
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' Household 1 has phone service: Yes
' Household 2 has phone service: No
' Household 3 has phone service: Yes
'
' Household 1 has cell phone service: Yes
' Household 2 has cell phone service: No
' Household 3 has cell phone service: Yes
'
' Household 1 has cell and land line service: Yes
' Household 2 has cell and land line service: No
' Household 3 has cell and land line service: No
'
' Household 1 has: LandLine, Cell, Internet
' Household 2 has: None
' Household 3 has: Cell, Internet
Poznámky
Bitová pole jsou obecně používána pro seznamy prvků, které mohou nastat v kombinaci, zatímco konstanty výčtu jsou obecně používány pro seznamy vzájemně se vylučujících prvků.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. Proto jsou bitová pole navržena tak, aby byla kombinována s bitovým nebo operací pro generování nepojmenovaných hodnot, zatímco výčtové konstanty nejsou.Therefore, bit fields are designed to be combined with a bitwise OR operation to generate unnamed values, whereas enumerated constants are not. Jazyky se liší v použití bitových polí v porovnání s konstantami výčtu.Languages vary in their use of bit fields compared to enumeration constants.
Atributy FlagsAttributeAttributes of the FlagsAttribute
AttributeUsageAttributeje použita na tuto třídu a její Inherited vlastnost určuje. false
AttributeUsageAttribute is applied to this class, and its Inherited property specifies false
. Tento atribut lze použít pouze pro výčty.This attribute can only be applied to enumerations.
Pokyny pro FlagsAttribute a EnumGuidelines for FlagsAttribute and Enum
FlagsAttribute Vlastní atribut pro výčet použijte pouze v případě, že bitová operace (a, nebo, exkluzivní nebo) má být provedena na numerické hodnotě.Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.
Definujte konstanty výčtu v mocninách dvou, tj. 1, 2, 4, 8 a tak dále.Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. To znamená, že jednotlivé příznaky v kombinovaných konstantách výčtu se nepřekrývají.This means the individual flags in combined enumeration constants do not overlap.
Zvažte vytvoření výčtové konstanty pro běžně používané kombinace příznaků.Consider creating an enumerated constant for commonly used flag combinations. Například pokud máte výčet, který se používá pro vstupně-výstupní operace se soubory,
Read = 1
které obsahují výčtové konstantyWrite = 2
a, zvažte vytvoření výčtovéRead
konstantyReadWrite = Read OR Write
, která kombinuje aWrite
Flag.For example, if you have an enumeration used for file I/O operations that contains the enumerated constantsRead = 1
andWrite = 2
, consider creating the enumerated constantReadWrite = Read OR Write
, which combines theRead
andWrite
flags. Bitová operace, která se používá k kombinování příznaků, může být navíc považována za pokročilý koncept za určitých okolností, které by neměly být požadovány pro jednoduché úlohy.In addition, the bitwise OR operation used to combine the flags might be considered an advanced concept in some circumstances that should not be required for simple tasks.Buďte opatrní, pokud definujete záporné číslo jako příznak s výčtovou konstantou, protože mnoho pozic příznaků může být nastavené na 1, což může způsobit matoucí kód a podporovat chyby kódování.Use caution if you define a negative number as a flag enumerated constant because many flag positions might be set to 1, which might make your code confusing and encourage coding errors.
Pohodlný způsob, jak otestovat, zda je příznak nastaven v číselné hodnotě, je provést bitovou a operaci mezi číselnou hodnotou a výčtovou konstantou, která nastaví všechny bity v číselné hodnotě na nulu, které neodpovídají příznaku. a potom otestujte, zda je výsledek této operace roven hodnotě příznak s výčtovou konstantou.A convenient way to test whether a flag is set in a numeric value is to perform a bitwise AND operation between the numeric value and the flag enumerated constant, which sets all bits in the numeric value to zero that do not correspond to the flag, then test whether the result of that operation is equal to the flag enumerated constant.
Použijte
None
jako název příznaku s výčtovou konstantou, jejíž hodnota je nula.UseNone
as the name of the flag enumerated constant whose value is zero. Nelze použítNone
výčtovou konstantu v bitové a operaci pro otestování příznaku, protože výsledek je vždy nula.You cannot use theNone
enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. K určení, zda jsou nastaveny jakékoli bity číselné hodnoty, však lze provést logickou, ne bitovou, porovnání mezi číselnou hodnotou aNone
výčtovou konstantou.However, you can perform a logical, not a bitwise, comparison between the numeric value and theNone
enumerated constant to determine whether any bits in the numeric value are set.Pokud vytvoříte výčet hodnot místo výčtu příznaků, je stále vhodné vytvořit
None
výčtovou konstantu.If you create a value enumeration instead of a flags enumeration, it is still worthwhile to create aNone
enumerated constant. Důvodem je, že ve výchozím nastavení je paměť použitá pro výčet inicializována modulem CLR (Common Language Runtime) na nulu.The reason is that by default the memory used for the enumeration is initialized to zero by the common language runtime. V důsledku toho, pokud nedefinujete konstantu, jejíž hodnota je nula, výčet bude při vytvoření obsahovat neplatnou hodnotu.Consequently, if you do not define a constant whose value is zero, the enumeration will contain an illegal value when it is created.Pokud je ve zjevném výchozím případě vaše aplikace musí představovat, zvažte použití výčtu konstanty, jejíž hodnota je nula, aby představovala výchozí hodnotu.If there is an obvious default case your application needs to represent, consider using an enumerated constant whose value is zero to represent the default. Pokud není žádný výchozí případ, zvažte použití výčtu konstanty, jejíž hodnota je nula, což znamená případ, který není reprezentován žádnou jinou výčtovou konstantou.If there is no default case, consider using an enumerated constant whose value is zero that means the case that is not represented by any of the other enumerated constants.
Nedefinujte hodnotu výčtu výhradně pro zrcadlení stavu samotného výčtu.Do not define an enumeration value solely to mirror the state of the enumeration itself. Nedefinujte například výčtovou konstantu, která pouze označí konec výčtu.For example, do not define an enumerated constant that merely marks the end of the enumeration. Pokud potřebujete určit poslední hodnotu výčtu, zkontrolujte tuto hodnotu explicitně.If you need to determine the last value of the enumeration, check for that value explicitly. Kromě toho můžete provést kontrolu rozsahu pro první a poslední výčtovou konstantu, pokud jsou všechny hodnoty v rozsahu platné.In addition, you can perform a range check for the first and last enumerated constant if all values within the range are valid.
Nezadávejte výčtové konstanty, které jsou vyhrazené pro budoucí použití.Do not specify enumerated constants that are reserved for future use.
Pokud definujete metodu nebo vlastnost, která přebírá výčtovou konstantu jako hodnotu, zvažte ověření hodnoty.When you define a method or property that takes an enumerated constant as a value, consider validating the value. Důvodem je, že můžete přetypovat číselnou hodnotu na typ výčtu i v případě, že číselná hodnota není definována ve výčtu.The reason is that you can cast a numeric value to the enumeration type even if that numeric value is not defined in the enumeration.
Konstruktory
FlagsAttribute() |
Inicializuje novou instanci třídy FlagsAttribute třídy.Initializes a new instance of the FlagsAttribute class. |
Vlastnosti
TypeId |
Při implementaci v odvozené třídě získá jedinečný identifikátor pro tento Attribute.When implemented in a derived class, gets a unique identifier for this Attribute. (Zděděno od Attribute) |
Metody
Equals(Object) |
Vrací hodnotu, která určuje, zda je tato instance rovna zadanému objektu.Returns a value that indicates whether this instance is equal to a specified object. (Zděděno od Attribute) |
GetHashCode() |
Vrátí kód hash této instance.Returns the hash code for this instance. (Zděděno od Attribute) |
GetType() |
Získá Type aktuální instance.Gets the Type of the current instance. (Zděděno od Object) |
IsDefaultAttribute() |
Při přepsání v odvozené třídě označuje, zda je hodnota této instance výchozí hodnotou pro odvozenou třídu.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Zděděno od Attribute) |
Match(Object) |
Při přepsání v odvozené třídě vrátí hodnotu, která označuje, zda je tato instance rovna zadanému objektu.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Zděděno od Attribute) |
MemberwiseClone() |
Vytvoří kopii aktuálního Objectbez podstruktury.Creates a shallow copy of the current Object. (Zděděno od Object) |
ToString() |
Vrací řetězec, který představuje aktuální objekt.Returns a string that represents the current object. (Zděděno od Object) |
Explicitní implementace rozhraní
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapuje sadu názvů na odpovídající sadu identifikátorů pro rozesílání.Maps a set of names to a corresponding set of dispatch identifiers. (Zděděno od Attribute) |
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Načte informace o typu pro objekt, který lze použít k získání informací o typu pro rozhraní.Retrieves the type information for an object, which can be used to get the type information for an interface. (Zděděno od Attribute) |
_Attribute.GetTypeInfoCount(UInt32) |
Získá počet rozhraní typu informací, které objekt poskytuje (0 nebo 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Zděděno od Attribute) |
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Poskytuje přístup k vlastnostem a metodám vystaveným objektem.Provides access to properties and methods exposed by an object. (Zděděno od Attribute) |