2010-07-06 60 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,其中鍵是枚舉名稱,可能帶有前綴。這樣您也可以輕鬆地本地化字符串值。