c#如何从自定义属性获取枚举?

时间:2017-08-29 12:11:14

标签: c# reflection enums attributes

这是MyEnum

public class CountryCodeAttr : EnumAttr
{
    public string Code { get; set; }
    public string Description { get; set; }
}

public enum CountryCode
{
    [CountryCodeAttr(Code = "Unknown", Description = "Unknown")]
    Unknown,
    [CountryCodeAttr(Code = "CH", Description = "Swiss", Currency="CHF")]
    CH
....

}

我怎样才能获得具有特定CountryCodeAttr的枚举?例如来自属性货币?

2 个答案:

答案 0 :(得分:0)

你需要从枚举类型中获取它:

CountryCode value = CountryCode.CH;
FieldInfo field = typeof(CountryCode).GetField(value.ToString());
var attr = field.GetCustomAttribute<CountryCodeAttr>();

答案 1 :(得分:0)

还有另一种方法可以使用泛型:

public static T GetAttribute<T>(Enum enumValue) where T: Attribute
{
    T attribute;

    MemberInfo memberInfo = enumValue.GetType().GetMember(enumValue.ToString())
                                    .FirstOrDefault();

    if (memberInfo != null)
    {
        attribute = (T) memberInfo.GetCustomAttributes(typeof (T), false).FirstOrDefault();
        return attribute;
    }
    return null;
}