关于.net:如何从VB.NET中的枚举中获取描述?

How to get the description from an enum in VB.NET?

本问题已经有最佳答案,请猛点这里访问。

我有一个在下面的枚举

1
2
3
4
5
6
7
Public Enum FailureMessages
  <Description("Failed by bending")>
  FailedCode1 = 0

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

每个系统有它自己的描述。例如,有它自己的"failedcode1描述由弯曲的失败。"

下面是我的(主分区),我想assign(字符串型变量)到相应的枚举。

1
2
3
4
5
 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。由于这些是用户添加的,因此可能会丢失一个或多个,如果缺少Attribute,我希望它返回Name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

用途:

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

您可以创建一个版本来获取Enum的所有描述:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

用途:

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

Of T使其更容易使用。传递类型将是:

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

注意,用名称填充组合意味着您需要解析结果以获取值。相反,我发现把所有的名称和值放在一个List(Of NameValuePairs)中更好/更容易把它们放在一起。

您可以将控件绑定到列表并使用DisplayMember向用户显示名称,而代码使用ValueMember返回实际键入的值。