2016-06-21 84 views
1

好了,所以我是新來的C#,對我的生活中,我無法理解究竟是什麼下面的代碼(從一個傳統的項目)是應該做的:標誌和<<枚舉操作? C#

[Flags] 
public enum EAccountStatus 
{ 
    None = 0, 
    FreeServiceApproved = 1 << 0, 
    GovernmentAccount = 1 << 1, 
    PrivateOrganisationAccount = 1 << 2, 
    All = 8 
} 

究竟做了<<運營商做這裏的枚舉?我們爲什麼需要這個?

+0

請檢查pmg的答案:http://stackoverflow.com/questions/3999922/why-use-the-bitwise-shift-operat or-for-values-in-a-c-enum-definition – manish

+0

想知道爲什麼他不使用'All = 1 << 3'? –

+0

謝謝@manish,這也是一個輝煌的答案:) –

回答

4

在幕後,枚舉實際上是一個int。
<<Bitwise Left Shift Operator
編寫這些代碼的等效方法是:

[Flags] 
public enum EAccountStatus 
{ 
    None = 0, 
    FreeServiceApproved = 1, 
    GovernmentAccount = 2, 
    PrivateOrganisationAccount = 4, 
    All = 8 
} 

請注意,此枚舉有Flag attribute

正如MSDN指出:

使用FlagsAttribute的枚舉自定義屬性只有在 按位運算(AND,OR,EXCLUSIVE OR)爲p在 數字值上執行。

這樣,如果你想有多個選項設置可以使用:

var combined = EAccountStatus.FreeServiceApproved | EAccountStatus.GovernmentAccount 

這相當於:

00000001 // =1 - FreeServiceApproved 
| 00000010 // =2 - GovernmentAccount 
--------- 
    00000011 //= 3 - FreeServiceApproved and GovernmentAccount 

this SO thread有大約flags attribute

一個比較好的解釋
+0

謝謝Avi,那是精美的解釋:) –

+0

:)我很高興我可以幫忙。 –

2

<<正在做什麼,即左移操作。

至於why in an enum而言,它只是計算表達式的方式枚舉允許表達式(和編譯時對其進行評估)

+0

謝謝,但爲什麼?爲什麼輪班在枚舉上離開操作? –

+0

@JoelMin,因爲它是計算1,2,4的簡單方法。使用'[Flags]'時,只需設置一個位。當你做'1 << 0'時,只有第0位被設置,當你做'1 << 2'時只有第2位被設置,等等。 –

+0

@ScottChamberlain解釋得很好。希望你現在理解它! –