2010-07-06 65 views
4

我正在处理的应用程序有很多枚举。如何存储枚举值的字符串描述?

这些值通常从应用程序中的下拉列表中选择。

什么是普遍接受的方式来存储这些值的字符串描述?

这里是手头上的当前问题:

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 

这只是好像这是可以做到更好,我不知道怎么样。

回答

11

您可以使用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

+0

感谢您的来源链接,为进一步扩展此功能提供了很好的建议。 – 2010-07-06 18:12:09

1

我见过的最常用的方法是用System.ComponentModel.DescriptionAttribute来注释枚举。

Public Enum MyEnum 

    <Description("Some Value")> 
    SomeValue = 1 
... 

然后获取的值,使用扩展方法(请原谅我的C#,我将它转换在一分钟内):

<System.Runtime.CompilerServices.Extension()> 
Public Function GetDescription(ByVal value As Enum) As String 
    Dim description As String = String.Empty 

    Dim fi As FieldInfo = value.GetType().GetField(value.ToString()) 
    Dim da = 
     CType(Attribute.GetCustomAttribute(fi,Type.GetType(DescriptionAttribute)), 
              DescriptionAttribute) 

    If da Is Nothing 
     description = value.ToString() 
    Else 
     description = da.Description 
    End If 

    Return description 
End Function 

这是我最好的刺伤其转换为VB。把它当作伪代码;)

+0

如果不需要本地化,则可以使用。 – driis 2010-07-06 17:10:20

3

我会把它们放在一个resource file,其中键是枚举名称,可能带有前缀。这样您也可以轻松地本地化字符串值。