Dot-Net

如何從 VB.NET 中的列舉中獲取描述?

  • February 13, 2016

我有如下列舉

Public Enum FailureMessages
 <Description("Failed by bending")>
 FailedCode1 = 0

 <Description("Failed by shear force")>
 FailedCode2 = 1
End Enum

每個列舉都有自己的描述。例如,FailedCode1 有自己的描述為“彎曲失敗”。

下面是我的主要 Sub() ,我想將一個變數(類型字元串)分配給相應的列舉。

Sub Main()
 Dim a As Integer = FailureMessages.FailedCode1
 Dim b As String 'I would b = Conresponding description of variable a above
 'that means: I would b will be "Failed by bending". How could I do that in .NET ?
End Sub 

誰能幫助我,我怎麼能在 VB.NET 中做到這一點

您需要使用Reflection來檢索Description. 由於這些是使用者添加的,因此可能會失去一個或多個,我希望它返回Name如果Attribute失去。

Imports System.Reflection
Imports System.ComponentModel

Public Shared Function GetEnumDescription(e As [Enum]) As String

   Dim t As Type = e.GetType()

   Dim attr = CType(t.
                   GetField([Enum].GetName(t, e)).
                   GetCustomAttribute(GetType(DescriptionAttribute)), 
                   DescriptionAttribute)

   If attr IsNot Nothing Then
       Return attr.Description
   Else
       Return e.ToString
   End If

End Function

用法:

Dim var As FailureMessages = FailureMessages.FailedCode1
Dim txt As String = GetDescription(var)

您可以創建一個版本來獲取所有說明Enum

Friend Shared Function GetEnumDescriptions(Of EType)() As String()
   Dim n As Integer = 0

   ' get values to poll
   Dim enumValues As Array = [Enum].GetValues(GetType(EType))
   ' storage for the result
   Dim Descr(enumValues.Length - 1) As String
   ' get description or text for each value
   For Each value As [Enum] In enumValues
       Descr(n) = GetEnumDescription(value)
       n += 1
   Next

   Return Descr
End Function

用法:

Dim descr = Utils.GetDescriptions(Of FailureMessages)()
ComboBox1.Items.AddRange(descr)

Of T使它更容易使用。傳遞類型將是:

Shared Function GetEnumDescriptions(e As Type) As String()
' usage:
Dim items = Utils.GetEnumDescriptions(GetType(FailureMessages))

請注意,使用名稱填充組合意味著您需要解析結果以獲取值。相反,我發現將所有名稱和值放入 aList(Of NameValuePairs)以將它們保持在一起會更好/更容易。

您可以將控制項綁定到列表並用於DisplayMember向使用者顯示名稱,而程式碼用於ValueMember取回實際鍵入的值。

引用自:https://stackoverflow.com/questions/25477732