與旗

2012-09-04 19 views
2

System.Enum組合考慮下面的枚舉:與旗

[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.EenType本身沒有任何地方。

+2

不應'Both'是'黑色| White'?你實現它的方式'Both'是'0'。 –

+0

謝謝。更正它。 –

+1

另外,在這種情況下,'Both'和'Either'似乎都會縮減,它們被實現爲位標誌。 –

回答

9

隨着標誌枚舉,一個 「任意的」 檢查可以推廣到(value & mask) != 0,所以這是:

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

假設您解決其實:

Both = Black | White 

(因爲Black & White是錯誤,這是零)

爲了完整性,「全部」檢查可概括爲(value & mask) == mask

+0

謝謝。我將Both和Either都包含在一起,以減少代碼分支,從而達到醜陋的算法。這應該做到這一點。 –

+0

@RaheelKhan你的'任一'枚舉值是沒有意義的,應該刪除。 –

+0

我假設這條語句不能進入枚舉本身,因爲它引用了一個運行時值。或者我錯過了什麼?枚舉應該允許getters。 –

1

爲什麼不乾脆:

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

這將意味着EnumType.Both也等於EnumType.Either? –

+2

這絕對是一個「兩個」。 「任一」的值沒有意義(至少,與「兩者」分開) –

-1

如何:

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

在這種情況下,設置'None = 1','Black = 2'和'White = 4'會更好,所以'Both'實際上與'Both'不同。 –

+0

完全錯過了那一個。感謝@nadirs捕捉它。 – Franky

+0

@nadirs'None'應該**在flags-enum中總是**爲零。對於Franky:請注意,在這裏(至少在最近的編輯之前),Both和Both都具有相同的值,這是不可避免的。 –