简体   繁体   中英

System.Enum combinations with Flags

Consider the following enumeration:

[System.Flags]
public enum EnumType: int
{
    None = 0,
    Black = 2,
    White = 4,
    Both = Black | White,
    Either = ???, // How would you do this?
}

Currently, I have written an extension method:

public static bool IsEither (this EnumType type)
{
    return
    (
        ((type & EnumType.Major) == EnumType.Major)
        || ((type & EnumType.Minor) == EnumType.Minor)
    );
}

Is there a more elegant way to achieve this?

UPDATE: As evident from the answers, EnumType.Either has no place inside the enum itself.

With flags enums, an "any of" check can be generalised to (value & mask) != 0 , so this is:

public static bool IsEither (this EnumType type)
{
    return (type & EnumType.Both) != 0;
}

assuming you fix the fact that:

Both = Black | White

(as Black & White is an error, this is zero)

For completeness, an "all of" check can be generalised to (value & mask) == mask .

Why not simply:

public enum EnumType
{
    // Stuff
    Either = Black | White
}

How about:

[System.Flags]
public enum EnumType: int
{
    None = 0,
    Black = 1,
    White = 2,
    Both = Black | White,
    Either = None | Both
}

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