【问题标题】:How to get the description from an enum in VB.NET? [duplicate]如何从 VB.NET 中的枚举中获取描述? [复制]
【发布时间】:2014-08-25 00:53:06
【问题描述】:

我有如下枚举

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 中做到这一点

【问题讨论】:

  • 不是重复的 - 这是用于 VB.NET,而不是 C#

标签: .net vb.net string enums


【解决方案1】:

您需要使用Reflection 来检索Description。由于这些是用户添加的,因此可能会丢失一个或多个,如果 Attribute 丢失,我希望它返回 Name

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))

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

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

【讨论】:

  • +1 好答案!可以通过提及您需要导入 System.ReflectionSystem.ComponentModel 来改进
  • 谢谢。最初,我将 Enum 变量命名为描述性的,但为了以后的报告目的,我需要一个适当的描述。你的功能有帮助!干杯!
猜你喜欢
  • 1970-01-01
  • 2011-02-08
  • 1970-01-01
  • 2011-05-21
  • 2012-10-15
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
相关资源
最近更新 更多