문제

So I came accross this code:

[Flags]
public enum Options
{
    NA = 0,
    OptionA = 1,
    OptionB = 2,
    OptionC = 4
}

Now, technically 'NA' is invalid, if the user doesn't want to select any Options, they just wont select any, and it will get saves to a nullable int. There is no "None" option. However, any time the user selects Options A-C, NA will always get added as well. If I change NA = 1, then OptionC = 8, everything works well. That portion makes sense. But how come NA will always be included in the user's option list if NA = 0?

Edit:

To clear some things up, NA is exclusive, but if I where to select OptionB, then when I view the selected Options, it will show I selected NA and OptionB.

도움이 되었습니까?

해결책

When you're adding Flags as an attribute on an enum, and a value that is 0, it will always be included if you use & to filter the values out.

That is due to that all required bits (none in that case) are always set.

다른 팁

If you are going to use an enum with the Flags attribute, then only use the value of 0 if you have an option that is exclusive of all other options (like None, for example). Then you test it with:

if (myOptions == Options.Na)

Testing with:

if ((myOptions & Options.Na) == Options.Na)

Will, of course, always return true.

Now the name Na suggest that it is exclusive of all the other options, so what's the problem?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top