如何存储枚举值的字符串描述?
我正在开发的应用程序有很多枚举。
这些值通常是从应用程序的下拉列表中选择的。
存储这些值的字符串描述的普遍接受的方式是什么?
这是当前的问题:
Public Enum MyEnum
SomeValue = 1
AnotherValue = 2
ObsoleteValue = 3
YetAnotherValue = 4
End Enum
下拉列表应具有以下选择:
Some Value
Another Value
Yet Another Value (Minor Description)
并非所有都适合枚举名称(其中一个的次要描述是一个示例),并且并非所有枚举值都是“当前”值。有些保留只是为了向后兼容和显示目的(即打印输出,而不是表格)。
这导致了以下代码情况:
For index As Integer = 0 To StatusDescriptions.GetUpperBound(0)
' Only display relevant statuses.
If Array.IndexOf(CurrentStatuses, index) >= 0 Then
.Items.Add(New ExtendedListViewItem(StatusDescriptions(index), index))
End If
Next
这似乎可以做得更好,但我不确定如何做。
The application I'm working on has lots of enumerations.
These values are generally selected from drop downs in the application.
What is the generally accepted way of storing the string description of these values?
Here is the current issue at hand:
Public Enum MyEnum
SomeValue = 1
AnotherValue = 2
ObsoleteValue = 3
YetAnotherValue = 4
End Enum
The drop down should have the following selections:
Some Value
Another Value
Yet Another Value (Minor Description)
Not all fit the name of the enumeration, (minor description on one is an example), and not all enumeration values are -current- values. Some remain only for backwards compatibility and display purposes (ie printouts, not forms).
This leads to the following code situation:
For index As Integer = 0 To StatusDescriptions.GetUpperBound(0)
' Only display relevant statuses.
If Array.IndexOf(CurrentStatuses, index) >= 0 Then
.Items.Add(New ExtendedListViewItem(StatusDescriptions(index), index))
End If
Next
This just seems like it could be done better, and I'm not sure how.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我见过的最常见的方法是使用 System.ComponentModel.DescriptionAttribute 注释枚举。
然后要获取该值,请使用扩展方法(请原谅我的 C#,我将在一分钟内转换它):
这是我将其转换为 VB 的最佳尝试。将其视为伪代码;)
The most common way I've seen is to annotate your enums with the
System.ComponentModel.DescriptionAttribute
.Then to fetch the value, use an extension method (excuse my C#, I'll convert it in a minute):
That's my best stab at converting it to VB. Treat it as pseudocode ;)
您可以使用
说明
属性(C# 代码,但应该翻译):来源
You could use the
Description
attribute (C# code, but it should translate):Source
我会将它们放入资源文件中,其中键是枚举名称,可能带有前缀。这样您还可以轻松本地化字符串值。
I would put them in a resource file, where the key is the enumeration name, possibly with a prefix. This way you can also localize the string values easily.