枚举成员是数字(通常是整数,但可以很长)。但它们不是可变的,并且在运行时不会改变。所以你的枚举等于:
Private Enum Item
ID = 0
Item = 1
Description = 2
End Enum
如果你想描述是一个字符串,那么类是一个更好的主意。枚举被用来引用或索引某些东西或限制/定义一个选择。像:
Public Property Stooge As Stooges
Friend Enum Stooges
Larry
Moe
Curly
Shemp
CurlyJoe
End Enum
Stooge属性必须是其中的一个值。在代码中它会显示文本(“moe”),但存储和整数(1)。用户将被显示在下拉列表等文本
您可以用枚举常量的描述联系起来:
Public Enum Stooges
<Description("Larry - Funny one")> Larry
<Description("Moe - 'Smart' One")> Moe
<Description("Curly - Sore One")> Curly
<Description("Shemp - One with bad haircut")> Shemp
<Description("CurlyJoe - Last one")> CurlyJoe
End Enum
要获得描述为一个单一的一个:
Public Shared Function GetDescription(ByVal EnumConstant As [Enum]) As String
Dim fi As Reflection.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() ' return enum name if no Descr
End If
End Function
用法:str = enumHelper.GetDescription(Stooge.Moe)
(enumHelper是静态/共享函数驻留的calss的名称)。
要得到所有的描述的字符串数组:
Public Shared Function GetDescriptions(ByVal type As Type) As String()
Dim n As Integer = 0
Dim enumValues As Array
Try
enumValues = [Enum].GetValues(type)
Dim Descr(enumValues.Length - 1) As String
For Each value As [Enum] In enumValues
Descr(n) = GetDescription(value)
n += 1
Next
Return Descr
Catch ex As Exception
MessageBox.Show(ex.Message)
Return Nothing
End Try
End Function
用法:Dim strEnum As String() = enumHelper.GetDescriptions(GetType(Stooges))
苹果和橘子。作为一个枚举,Item.ID将只是一个整数。如果你想要一个字符串,然后使用一个类,但这些成员可能应该是属性(和“朋友”,除非课堂以外的任何东西不能读取或写入他们) – Plutonix