2

考虑以下枚举:

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

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

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

有没有更优雅的方法来实现这一点?

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

4

3 回答 3

9

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

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

假设您解决了以下事实:

Both = Black | White

(作为Black & White一个错误,这是零)

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

于 2012-09-04T10:58:14.420 回答
1

为什么不简单:

public enum EnumType
{
    // Stuff
    Either = Black | White
}
于 2012-09-04T10:55:24.807 回答
-1

怎么样:

[System.Flags]
public enum EnumType: int
{
    None = 0,
    Black = 1,
    White = 2,
    Both = Black | White,
    Either = None | Both
}
于 2012-09-04T10:58:59.033 回答