还有其他几种选择。
一种是获取枚举中使用的名称。例如:
Friend Enum ImgFormat
Bitmap
GIF
JPeg
TIFF
PNG
End Enum
Dim ImgNames() As String
...
ImgNames = [Enum].GetNames(GetType(ImgFormat))
如果你的名字不够友好,用描述来装饰它们:
Imports System.ComponentModel
Friend Enum ImgFormat
<Description("Bitmap (BMP)")> Bitmap
<Description("Graphic Interchange (GIF)")> GIF
<Description("Jpg/JPeg (JPG)")> JPeg
<Description("Tagged Image (TIFF)")> TIFF
<Description("Portable Graphics (PNG)")> PNG
End Enum
要获得描述,需要涉及的反射:
Imports System.Reflection
Imports System.ComponentModel
Public Class EnumConverter
' gets a single enum description
Public Shared Function GetEnumDescription(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
' get all the enum descriptions:
Public Shared Function GetEnumDescriptions(ByVal type As Type) As String()
Dim n As Integer = 0
Dim enumValues As Array = [Enum].GetValues(type)
Dim Descr(enumValues.Length - 1) As String
For Each value As [Enum] In enumValues
Descr(n) = GetEnumDescription(value)
n += 1
Next
Return Descr
End Function
End Class
要使用:
Dim ImgNames() As String = EnumConverter.GetEnumDescriptions(ImgFormat)
ImgNames(ImgFormat.GIF)
将是“图形交换 (GIF)”
如果枚举值不是默认的 0、1、2 ... 如果这是一个问题(确实是),这将中断,然后围绕它构建一个类来存储带有枚举值的名称或描述。与其构建一个类来创建伪枚举,不如创建一个由描述和枚举值组成的名称-值对列表。