還有另一種方法可以做到這一點,它相當優雅,所以我想我會分享一些我最近寫的東西。它具有需要很少數學的好處,所以我認爲它不太容易出錯。這是非常可讀的,恕我直言。
[Flags][Serializable]
public enum ScopeType : int
{
Unknown = 0,
Global = 1,
Namespace = Global << 1,
Class = Namespace << 1,
Struct = Class << 1,
Interface = Struct << 1,
Enum = Interface << 1,
Function = Enum << 1,
Property = Function << 1,
PropertyGetter = Property << 1,
PropertySetter = PropertyGetter << 1,
Using = PropertySetter << 1,
If = Using << 1,
ElseIf = If << 1,
Else = ElseIf << 1,
Switch = Else << 1,
Case = Switch << 1,
For = Case << 1,
While = For << 1,
DoWhile = While << 1,
Lambda = DoWhile << 1,
Try = Lambda << 1,
Catch = Try << 1,
Finally = Catch << 1,
Initializer = Finally << 1,
Checked = Initializer << 1,
Unchecked = Checked << 1,
Unsafe = Unchecked << 1,
Lock = Unsafe << 1,
Fixed = Lock << 1,
// I can also group flags together using bitwise-OR.
PropertyAccessor = PropertyGetter | PropertySetter,
TypeDefinition = Class | Struct | Interface | Enum,
TryCatchFinally = Try | Catch | Finally,
Conditional = If | ElseIf | Else,
Branch = Conditional | Case | TryCatchFinally,
Loop = For | While | DoWhile
}
注意:由於枚舉繼承自System.Int32
,我只能定義32個標誌。如果你需要更多,你將不得不使用一個更大的整數(System.Int64
),創建多個枚舉並將它們鏈接在一起,或者只是用一堆布爾值創建一個類。
這些2個代碼片段(fragments)產生的IL代碼是相同的。 – 2010-01-25 17:36:14
現貨在此代碼的bug:BackupOperator = 1073714824.您可以通過說出BackupOperator = 1 << 30 – 2010-01-25 18:53:06
感謝您的信息全部,我將使用第一形式給出避免在首位的缺陷,因爲它似乎更好除了最簡單的情況外。 – Nate 2010-01-26 14:09:28