.net 如何存储枚举值的字符串描述?

rbpvctlc  于 2022-12-05  发布在  .NET
关注(0)|答案(3)|浏览(229)

我正在处理的应用程序有很多枚举。
这些值通常从应用程序的下拉唐斯中选择。
存储这些值的字符串描述的公认方式是什么?
以下是当前的问题:

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

这似乎可以做得更好,我不知道怎么做。

qojgxg4l

qojgxg4l1#

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

8i9zcol2

8i9zcol22#

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

cngwdvgl

cngwdvgl3#

我见过的最常见的方法是用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的最佳尝试。)

相关问题