0

如何引用 中的属性enums

如果我有以下enum类型,如何引用该枚举类型的特定值的属性?

public enum PersonGender
{
    Unknown = 0,
    Male = 1,
    Female = 2,
    Intersex = 3,
    Indeterminate = 3,

    [EnumMember("Not Stated")]
    NonStated = 9,

    [EnumMember("Inadequately Described")]
    InadequatelyDescribed = 9
}
4

3 回答 3

4

以下代码使用 .Net 4.5 扩展方法GetCustomAttribute来获取字段的自定义属性

Type enumType = typeof(PersonGender);
var value = enumType.GetField(PersonGender.NonStated.ToString())
                    .GetCustomAttribute<EnumMemberAttribute>().Value; 
// returns "Not Stated"

当然,您应该为字段和自定义属性添加空检查

于 2013-03-17T07:46:37.457 回答
1

您可以使用反射

例如:

    class EnumMemberAttribute : Attribute
    {
        private String name;

        public String Name
        {
            get { return this.name; }
            set { this.name = value; }
        }

        public EnumMemberAttribute(String name)
        {
            this.name = name;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(PersonGender);
            MemberInfo[] members = type.GetMember(PersonGender.NonStated.ToString());
            Object[] attributes = members[0].GetCustomAttributes(typeof(EnumMemberAttribute),
                false);
            Console.WriteLine(((EnumMemberAttribute)attributes[0]).Name);            
        }
    } 
于 2013-03-17T07:46:33.917 回答
0

首先,将 InadequatelyDescribed 设置为 NonStated 以外的另一个值。

其次, EnumMembers 的正确语法是

[EnumMember(Value = "Not Stated")]

这是解决方案 - 在.NET 4.0和 4.5 中工作:

PersonGender pg = PersonGender.InadequatelyDescribed;
string pgName = Enum.GetName(typeof(PersonGender), pg);

var t = typeof(PersonGender);
var info = t.GetMember(pgName);
var att = info[0].GetCustomAttributes(typeof(EnumMemberAttribute), false);

if (att.Length > 0)
{
    Console.WriteLine(((EnumMemberAttribute)att[0]).Value);
}
else
{
    Console.WriteLine(pgName);
}
于 2013-03-17T07:40:50.787 回答