Changing a flag based on a boolean
Does any have a more elegant way of doing this?
[Flags]
public enum SomeFlaggedEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4
}
private SomeFlaggedEnum _myFlags;
public bool EnabledValue1
{
set
{
if (value)
{
_myFlags |= SomeFlaggedEnum.Value1;
}
else
{
_myFlags &= ~SomeFlaggedEnum.Value1;
}
}
}
I know there is probably a simple answer and开发者_运维技巧 I'm just way over thinking it...
EDIT: The enum was incorrect as pointed out in one of the answers. This was only in this example and not in the actual code.
I mean, you could do:
_myFlags = value ? myFlags | SomeFlaggedEnum.Value1 : myFlags & ~SomeFlaggedEnum.Value1;
But I think your solution is fine.
Well, you could use a conditional:
_myFlags = value ? _myFlags | SomeFlaggedEnum.Value1
: _myFlags & ~SomeFlaggedEnum.Value1;
It looks like it'd get pretty ugly if you had a property per flag for setting it, assuming you'll have more than 3 flags. Would it not be easier to go for a single method where you can say which flags to set?
public void EnableFlag(SomeFlaggedEnum value, bool set) {
_myFlags = set ? value | _myFlags : ~value & _myFlags;
}
EnableFlag(SomeFlaggedEnum.Value1, true);
Make a generic setter for flags (there is already a generic "HasFlag" in the Enum class, but an extension like this will complement it.
public static class EnumExtensions
{
public static T SetFlags<T>(this T value, T flags, bool on) where T : struct
{
long lValue = Convert.ToInt64(value);
long lFlag = Convert.ToInt64(flags);
if (on)
{
lValue |= lFlag;
}
else
{
lValue &= (~lFlag);
}
return (T)Enum.ToObject(typeof(T), lValue);
}
}
Once you have that, you can make properties for each flag (but that quickly gets messy), or simply delegate getting and setting flags to HasFlag/SetFlag
Your setter is fine.
The issue is that using FlagsAttribute
doesn't make the compiler choose useful values for using the enum members as flags. SomeFlaggedEnum.Value1
is zero, because it's the first declared value in the enumeration, and so it doesn't represent a bit flag at all.
Try
[Flags]
public enum SomeFlaggedEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4
}
精彩评论