简体   繁体   English

CLR - 使用“Flags”属性声明枚举

[英]CLR - Declare enum with "Flags" attribute

I have the following Enum in CLR / CLI:我在 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.在 C# 中,如果我想创建选定枚举的组合,我曾经在枚举的声明之前添加[Flags]属性。

Does anything similar to that exist in C++ CLR? C++ CLR 中是否存在类似的东西?

The FlagsAttribute in C# just indicates that the enumeration can be treated as a bit field.所述FlagsAttribute在C#只是表明枚举可以作为一个位域进行处理。

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:真正重要的是您适当地定义枚举值,以便可以对它们执行 AND、OR、NOT 和 XOR 按位运算,即您应该为每个枚举值分配 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. [Flags]不会自动使枚举值成为 2 的幂。

What does the [Flags] Enum Attribute mean in C#? [Flags] 枚举属性在 C# 中是什么意思?

You can use the flags attribute in C++/CLI like this:您可以像这样在 C++/CLI 中使用 flags 属性:

[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. [Flags] 不会自动使枚举值成为 2 的幂。 But it can be required by some static code analysis tools:但是一些静态代码分析工具可能需要它:

PVS Studio PVS工作室

Sonar Lint声纳皮棉

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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