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 に答える