如何从VB.NET中枚举的描述? [英] How to get the description from an enum in VB.NET?
问题描述
我有枚举如下
Public Enum FailureMessages
<Description("Failed by bending")>
FailedCode1 = 0
<Description("Failed by shear force")>
FailedCode2 = 1
End Enum
每个枚举都有它自己的描述。例如,失败的code1有自己描述为通过弯曲失败。
Each enum has its own description. For example, FailedCode1 has its own description as "Failed by bending".
下面是我的主要子(),我想为变量赋值(字符串类型)到相应的枚举。
Below is my main Sub() where I would like to assign a variable (type string) to the corresponding enum.
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
Can anyone please help me, how could I do that in VB.NET
推荐答案
您需要使用反射来得到它:
You need to use Reflection to get at it:
Imports System.Reflection
' you already know about this one since you are using <Description>, but:
Imports System.ComponentModel
Friend Shared Function GetDescription(ByVal EnumConstant As [Enum]) As String
Dim fi As FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
Dim attr() As DescriptionAttribute =
DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute),
False), DescriptionAttribute())
If attr.Length > 0 Then
Return attr(0).Description
Else
Return EnumConstant.ToString()
End If
End Function
用法:
Dim var As FailureMessages = FailureMessages.FailedCode1
Dim txt As String = GetDescription(var)
请注意,如果你错过了一个描述为一个或多个值,它会用这个名字来代替。您可以创建一个版本,让所有的描述为枚举
:
Note that if you miss a Description for one or more values, it will use the name instead. You can create a version to get all the Descriptions for an Enum
:
Public Shared Function GetDescriptions(T As Type) As String()
If T.IsEnum = False Then
Return New String() {}
End If
Dim values = [Enum].GetValues(T)
Dim descr As New List(Of String)
For Each v In values
' calls the first method to get the descr/name
descr.Add(GetDescription(CType(v, [Enum])))
Next
Return descr.ToArray()
End Function
用法:
Dim descr = EnumDescrConverter.GetDescriptions(GetType(FailureMessages))
ComboBox1.Items.AddRange(descr)
如果你不使用一个简单的NameValuePair类型的类,以保持名称/ descr和值在一起,你会需要像 GetDescriptionValue()
将文本转换回一个枚举值。这是 GetDescription
逻辑正好相反。
If you dont use a simple NameValuePair type class to keep the name/descr and value together you will need something like GetDescriptionValue()
to convert the text back to an Enum value. That is just the reverse of the GetDescription
logic.
这篇关于如何从VB.NET中枚举的描述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!