I have an enum (flag)
[Flags]
public enum DisplayMode
{
None,
Dim,
Inverted,
Parse,
Italics,
Bold
}
I want to assign two of the flags to a variable, like this:
var displayFlags = DisplayMode.Parse | D开发者_运维技巧isplayMode.Inverted;
However, when I debug and hover over this variable immediately after it is assigned, it says displayFlags
is DisplayMode.Dim | DisplayMode.Inverted
.
What am I missing/not understanding?
You've missed assigning the flags sensible values, e.g.:
[Flags]
public enum DisplayMode
{
None = 0,
Dim = 1,
Inverted = 2,
Parse = 4,
Italics = 8,
Bold = 16
}
That way each value has a separate bit in the numeric representation.
If you don't trust your ability to double values, you can use bit shifting:
[Flags]
public enum DisplayMode
{
None = 0,
Dim = 1 << 0,
Inverted = 1 << 1,
Parse = 1 << 2,
Italics = 1 << 3,
Bold = 1 << 4
}
From the documentation from 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.
...
By default, an enum will assign consecutive values to the members. So you've essentially got:
[Flags]
public enum DisplayMode
{
None = 0,
Dim = 1,
Inverted = 2,
Parse = 3,
Italics = 4,
Bold = 5
}
That doesn't work for binary/flags. So you need to be explicit:
[Flags]
public enum DisplayMode
{
None = 0,
Dim = 1,
Inverted = 2,
Parse = 4,
Italics = 8,
Bold = 16
}
You're not providing appropriate values to your enum upon declaration:
[Flags]
public enum DisplayMode
{
None = 0,
Dim = 1,
Inverted = 2,
Parse = 4,
Italics = 8,
Bold = 16
}
You need to specify the values of the flags explicitly. As declared, Parse is 3, which is Dim | Inverted.
Try
[Flags]
public enum DisplayMode
{
None = 0,
Dim = 1 << 0,
Inverted = 1 << 1,
Parse = 1 << 2,
Italics = 1 << 3,
Bold = 1 << 4
}
You need to define the enumertion values as powers of two:
[Flags]
public enum DisplayMode
{
None = 1,
Dim = 2,
Inverted = 4,
Parse = 8,
Italics = 16,
Bold = 32
}
More information here: http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx
Since you are using flags, you need to think in binary terms so you should increase your values by a multitude of 2 each time. For example, think:
0001 = 0x01,
0010 = 0x02,
0100 = 0x04,
1000 = 0x08
and so on...
精彩评论