我正在处理的应用程序有很多枚举。
这些值通常从应用程序的下拉列表中选择。
存储这些值的字符串描述的普遍接受的方式是什么?
这是当前的问题:
Public Enum MyEnum
SomeValue = 1
AnotherValue = 2
ObsoleteValue = 3
YetAnotherValue = 4
End Enum
下拉菜单应有以下选择:
Some Value
Another Value
Yet Another Value (Minor Description)
并非所有枚举都符合枚举名称(对一个的次要描述是一个示例),并且并非所有枚举值都是 -current- 值。有些仅用于向后兼容和显示目的(即打印输出,而不是表格)。
这导致以下代码情况:
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
这似乎可以做得更好,我不确定如何。
最佳答案
您可以使用 Description
属性(C#代码,但应该翻译):
public enum XmlValidationResult
{
[Description("Success.")]
Success,
[Description("Could not load file.")]
FileLoadError,
[Description("Could not load schema.")]
SchemaLoadError,
[Description("Form XML did not pass schema validation.")]
SchemaError
}
private string GetEnumDescription(Enum value)
{
// Get the Description attribute value for the enum value
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
Source