我有一个枚举(标志)
[Flags]
public enum DisplayMode
{
None,
Dim,
Inverted,
Parse,
Italics,
Bold
}
我想将两个标志分配给一个变量,如下所示:
var displayFlags = DisplayMode.Parse | DisplayMode.Inverted;
但是,当我调试并在分配后立即将鼠标悬停在该变量上时,它说 displayFlags
is DisplayMode.Dim | DisplayMode.Inverted
.
我缺少/不理解什么?
最佳答案
您错过了为标志分配合理的值,例如:
[Flags]
public enum DisplayMode
{
None = 0,
Dim = 1,
Inverted = 2,
Parse = 4,
Italics = 8,
Bold = 16
}
这样每个值在数字表示中都有一个单独的位。
如果您不相信自己将值加倍的能力,可以使用位移:
[Flags]
public enum DisplayMode
{
None = 0,
Dim = 1 << 0,
Inverted = 1 << 1,
Parse = 1 << 2,
Italics = 1 << 3,
Bold = 1 << 4
}
来自 FlagsAttribute
的文档:
Guidelines for FlagsAttribute and Enum
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.
Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.
...
关于C# 标志问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7534580/