简体   繁体   中英

CLR - Declare enum with "Flags" attribute

I have the following Enum in CLR / CLI:

public enum class Days
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
};

In C#, if I wanted to create a combination of the selected enums, I used to add [Flags] attribute before the declaration of the enum.

Does anything similar to that exist in C++ CLR?

The FlagsAttribute in C# just indicates that the enumeration can be treated as a bit field.

What really matters is that you define the enumeration values appropriately so that AND, OR, NOT and XOR bitwise operations can be performed on them, ie you should assign each enumeration value the next greater power of 2:

public enum class Days
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 4,
    Wednesday = 8,
    Thursday = 16,
    Friday = 32,
    Saturday = 64
};

[Flags] does not automatically make the enum values powers of two.

What does the [Flags] Enum Attribute mean in C#?

You can use the flags attribute in C++/CLI like this:

[System::Flags]
public enum class Days : int
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 4,
    Wednesday = 8,
    Thursday = 16,
    Friday = 32,
    Saturday = 64
};

[Flags] does not automatically make the enum values powers of two. But it can be required by some static code analysis tools:

PVS Studio

Sonar Lint

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM