Vb.net 如何获取枚举值、字符串和描述
我正在尝试循环遍历枚举并从中提取值、字符串和描述?我该怎么做Vb.net 如何获取枚举值、字符串和描述,vb.net,enums,Vb.net,Enums,我正在尝试循环遍历枚举并从中提取值、字符串和描述?我该怎么做 Enum Fruits <Description("$1.99/lb")> Apple = 1 <Description("$0.99/lb")> Banana= 2 <Description("$3.99/lb")> Orange= 3 End Enum 我想得到: ID:1个苹果每磅1.99美元 ID:2根香蕉每磅0.99美元 ID:3个橙子是每
Enum Fruits
<Description("$1.99/lb")> Apple = 1
<Description("$0.99/lb")> Banana= 2
<Description("$3.99/lb")> Orange= 3
End Enum
我想得到:
ID:1个苹果每磅1.99美元
ID:2根香蕉每磅0.99美元
ID:3个橙子是每磅3.99美元
谢谢你的帮助 这是一种非常糟糕的数据元素管理方法:每次香蕉价格上涨时,您都必须更改代码。应为静态项保留说明。例:
Friend Enum ImgSizes
<Description("Large, 1600x900")> Lg = 1600
<Description("Medium, 1280x720")> Med = 1280
<Description("Small, 720x480")> Sm = 720
End Enum
您的循环需要工作,并且需要使用OPTION STRICT。循环遍历这些值以获得所需的信息。索引变量必须作为结果
否则它不是枚举/Friuts,而是整数或对象,没有任何效果
For Each v As Fruit In [Enum].GetValues(GetType(Fruits))
returnText = String.Format("ID: {0} {1} is {2}",
Convert.ToInt32(v), v.ToString,
GetDescription(GetType(v))
Next
1.v、 value向我抛出了一个错误,说“value”不是成员。您是对的,这是一种管理数据元素的糟糕方法,幸运的是,这些只是虚拟数据。:)我在两分钟内想到了一些东西。我想我应该多考虑一下。我的错误是复制了太多的代码。它应该是
Convert.ToInt32(v)
加上橙子太贵了;)
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
For Each v As Fruit In [Enum].GetValues(GetType(Fruits))
returnText = String.Format("ID: {0} {1} is {2}",
Convert.ToInt32(v), v.ToString,
GetDescription(GetType(v))
Next