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,我可以的
您需要使用
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) |
您可以创建一个版本来获取
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) |
1 2 3 | Shared Function GetEnumDescriptions(e As Type) As String() ' usage: Dim items = Utils.GetEnumDescriptions(GetType(FailureMessages)) |
注意,用名称填充组合意味着您需要解析结果以获取值。相反,我发现把所有的名称和值放在一个
您可以将控件绑定到列表并使用