简体   繁体   中英

Do C# enum flags have to be sequential

In C#, do enum flags have to be sequential? or can you leave gaps? and still perform bit-wise comparisons? ie, can you do the following:

[Flags]
public enum MyEnum
{
    None = 0,
    IsStarred = 1,
    IsDone = 128
}

There is nothing that requires them to be sequential.

Your enum definition is fine and will compile without issue.

The issue of readability and the principle of least astonishment, however have been greatly compromised...

There is nothing wrong with the code you have posted. This is absolutely fine:

[Flags]
public enum MyEnum
{
    None = 0,
    IsStarred = 1,
    IsDone = 128
}

And so is this:

[Flags]
public enum MyEnum
{
    IsStarred = 1,
    IsDone = 128
    None = 0,
    SomethingElse = 4,
}

Just remember that the FlagsAttribute does not enforce your values to be bit masks.

No such requirement. What you have is fine, assuming you capitalize [Flags] .

它们不必是顺序的。

Yes, you can do that. It's up to you.

No, they don't have to be sequential. Compile your code and see it for yourself

Not only can you do that, but you can also do this:

public enum MyEnum
{
    None,
    IsStarred,
    IsDone = 128
}

or

public enum MyEnum
{
    None = 5,
    IsStarred,
    IsDone = 128
}

here's a link to more examples: http://www.dotnetperls.com/enum

Squental enums dont need to have the Flags attribute. But it is a best practice. You can read more here: http://msdn.microsoft.com/en-us/library/ms229062.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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