System.Enum与Flags的组合

Rah*_*han 2 .net c# enums

请考虑以下枚举:

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

目前,我已经编写了一个扩展方法:

public static bool IsEither (this EnumType type)
{
    return
    (
        ((type & EnumType.Major) == EnumType.Major)
        || ((type & EnumType.Minor) == EnumType.Minor)
    );
}
Run Code Online (Sandbox Code Playgroud)

是否有更优雅的方式来实现这一目标?

更新:从答案中可以看出,EnumType.Either在枚举本身中没有位置.

Mar*_*ell 9

使用标志枚举,可以将"任何"检查推广到(value & mask) != 0,所以这是:

public static bool IsEither (this EnumType type)
{
    return (type & EnumType.Both) != 0;
}
Run Code Online (Sandbox Code Playgroud)

假设您修复了以下事实:

Both = Black | White
Run Code Online (Sandbox Code Playgroud)

(因为Black & White是错误,这是零)

为了完整起见,可以将"全部"检查推广到(value & mask) == mask.