Neatest way to 'OR' all values in a Flagged Enum?

后端 未结 6 923
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 09:43

Given the enum:

[Flags]
public enum mytest
{
    a = 1,
    b = 2,
    c = 4
}

I\'ve come up with two ways to represent all va

6条回答
  •  余生分开走
    2021-01-17 10:03

    If it makes sense to have an All member, just provide it directly:

    [Flags]
    public enum mytest
    {
        a = 1,
        b = 2,
        c = 4,
        All = 7
    }
    

    Though, a more idiomatic way to write these could be:

    [Flags]
    public enum MyTest
    {
        A = 1,
        B = 1 << 0x01,
        C = 1 << 0x02,
        All = A | B | C
    }
    

    This shows the logical progression of the enum values, and in the All case, makes it easy to add another member.

提交回复
热议问题