-3

如何使用DescriptionAttibute来实现以下目标enums?注意枚举值中的空格。

public enum PersonGender
    {
        Unknown = 0,
        Male = 1,
        Female = 2,
        Intersex = 3,
        Indeterminate = 3,
        Non Stated = 9,
        Inadequately Described = 9
    }
4

1 回答 1

3

例如,您可以这样使用:

这是我们的枚举:

public enum MyEnum
{
   [Description("Description for Foo")]
   Foo,
   [Description("Description for Bar")]
   Bar
}

以及我们获取属性的方法。

public static string GetDescription(this Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
             DescriptionAttribute attr =
                    Attribute.GetCustomAttribute(field,
                    typeof(DescriptionAttribute)) as DescriptionAttribute;
              if (attr != null)
              {
                   return attr.Description;
              }
        }
    }
    return null;
}

你可以得到描述:

  MyEnum x = MyEnum.Foo;
  string description = x.GetDescription();

资源

于 2013-03-17T08:10:12.617 回答