確定 Enum 是否指定了 FlagsAttribute

下一個示例可用於確定列舉是否指定了 FlagsAttribute 。使用的方法基於 反射

這個例子將給出一個 True 結果:

Dim enu As [Enum] = New FileAttributes()
Dim hasFlags As Boolean = enu.GetType().GetCustomAttributes(GetType(FlagsAttribute), inherit:=False).Any()
Console.WriteLine("{0} Enum has FlagsAttribute?: {1}", enu.GetType().Name, hasFlags)

這個例子將給出一個 False 結果:

Dim enu As [Enum] = New ConsoleColor()
Dim hasFlags As Boolean = enu.GetType().GetCustomAttributes(GetType(FlagsAttribute), inherit:=False).Any()
Console.WriteLine("{0} Enum has FlagsAttribute?: {1}", enu.GetType().Name, hasFlags)

我們可以設計一個像這樣的通用用法擴充套件方法:

<DebuggerStepThrough>
<Extension>
<EditorBrowsable(EditorBrowsableState.Always)>
Public Function HasFlagsAttribute(ByVal sender As [Enum]) As Boolean
    Return sender.GetType().GetCustomAttributes(GetType(FlagsAttribute), inherit:=False).Any()
End Function

用法示例:

Dim result As Boolean = (New FileAttributes).HasFlagsAttribute()