如何获取枚举的自定义属性值?

60

我有一个枚举类型,其中每个成员都有一个自定义的属性。如何检索存储在每个属性中的值?

目前我是这样做的:

var attributes = typeof ( EffectType ).GetCustomAttributes ( false );
foreach ( object attribute in attributes )
{
    GPUShaderAttribute attr = ( GPUShaderAttribute ) attribute;
    if ( attr != null )
        return attr.GPUShader;
}
return 0;

另一个问题是,如果找不到,我应该返回什么? 0 隐式可转换为任何枚举类型,对吧?这就是我返回它的原因。

忘记提到了,上面的代码会为每个枚举成员返回0。


1
可能是重复的问题:枚举成员应该使用哪个AttributeTarget? - Hans Passant
2
不,这是不同的。在这里,我只是尝试使用反射获取设置在枚举成员上的自定义属性。 - Joan Venge
1
可能是获取枚举值的属性的重复。 - Roman Starkov
7个回答

96

尝试使用通用方法

属性:

class DayAttribute : Attribute
{
    public string Name { get; private set; }

    public DayAttribute(string name)
    {
        this.Name = name;
    }
}

枚举:

enum Days
{
    [Day("Saturday")]
    Sat,
    [Day("Sunday")]
    Sun,
    [Day("Monday")]
    Mon, 
    [Day("Tuesday")]
    Tue,
    [Day("Wednesday")]
    Wed,
    [Day("Thursday")]
    Thu, 
    [Day("Friday")]
    Fri
}

通用方法:

        public static TAttribute GetAttribute<TAttribute>(this Enum value)
        where TAttribute : Attribute
    {
        var enumType = value.GetType();
        var name = Enum.GetName(enumType, value);
        return enumType.GetField(name).GetCustomAttributes(false).OfType<TAttribute>().SingleOrDefault();
    }
调用:
        static void Main(string[] args)
    {
        var day = Days.Mon;
        Console.WriteLine(day.GetAttribute<DayAttribute>().Name);
        Console.ReadLine();
    }

结果:

星期一


7
希望我能点赞这个回答100遍!!太棒了 :-) - Gericke
2
好的,可以运行...但是如果您没有为特定的枚举值声明属性,可能会在空值上调用.Name。即,在调用.Name之前,应检查day.GetAttribute<DayAttribute>() != null。 - joedotnot

46

你正在尝试做的事情有点混乱,因为你必须使用反射:

public GPUShaderAttribute GetGPUShader(EffectType effectType)
{
    MemberInfo memberInfo = typeof(EffectType).GetMember(effectType.ToString())
                                              .FirstOrDefault();

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

    return null;
}

这将返回一个与枚举值EffectType中标记的GPUShaderAttribute相关的实例。您必须在EffectType枚举的特定值上调用它:

GPUShaderAttribute attribute = GetGPUShader(EffectType.MyEffect);

一旦您获得了属性的实例,您就可以从中获取标记在各个枚举值上的特定值。


谢谢,老兄。它起作用了。我不知道会这么复杂。但这是最简单的方法,对吧?另外,你知道为什么我的版本不起作用吗?我以为由于枚举无法实例化,使用enum.getCustomAttributes就可以了。 - Joan Venge
1
@Joan:就我所知,这是最简单的方法。你的方法不起作用,因为你获得的是枚举类型上定义的属性,而不是类型值上的属性。 - adrianbanks
谢谢Adrian,现在我明白了。 - Joan Venge

29

还有一种使用泛型的方法可以做到这一点:

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;
}

2
我喜欢这个,但它没有考虑到具有相同属性的多个实例的可能性。我采用了你的方法,并修改为使用T[]而不是T,然后删除了GetCustomAttributes上的FirstOrDefault()。 - Kevin Heidt

2
假设有一个名为GPUShaderAttribute的变量:
[AttributeUsage(AttributeTargets.Field,AllowMultiple =false)]
public class GPUShaderAttribute: Attribute
{
    public GPUShaderAttribute(string value)
    {
        Value = value;
    }
    public string Value { get; internal set; }
}

然后我们可以编写一些通用方法,返回一个枚举值和GPUShaderAttribute对象的字典。

    /// <summary>
    /// returns the attribute for a given enum
    /// </summary>        
    public static TAttribute GetAttribute<TAttribute>(IConvertible @enum)
    {
        TAttribute attributeValue = default(TAttribute);
        if (@enum != null)
        {
            FieldInfo fi = @enum.GetType().GetField(@enum.ToString());
            attributeValue = fi == null ? attributeValue : (TAttribute)fi.GetCustomAttributes(typeof(TAttribute), false).DefaultIfEmpty(null).FirstOrDefault();

        }
        return attributeValue;
    }

然后使用这种方法返回整个集合。
/// <summary>
/// Returns a dictionary of all the Enum fields with the attribute.
/// </summary>
public static Dictionary<Enum, RAttribute> GetEnumObjReference<TEnum, RAttribute>()
{
    Dictionary<Enum, RAttribute> _dict = new Dictionary<Enum, RAttribute>();
    Type enumType = typeof(TEnum);
    Type enumUnderlyingType = Enum.GetUnderlyingType(enumType);
    Array enumValues = Enum.GetValues(enumType);
    foreach (Enum enumValue in enumValues)
    {
        _dict.Add(enumValue, GetAttribute<RAttribute>(enumValue));
    }

    return _dict;
}

如果你只需要一个字符串值,我建议选择稍微不同的方法。
    /// <summary>
    /// Returns the string value of the custom attribute property requested.
    /// </summary>
    public static string GetAttributeValue<TAttribute>(IConvertible @enum, string propertyName = "Value")
    {
        TAttribute attribute = GetAttribute<TAttribute>(@enum);
        return attribute == null ? null : attribute.GetType().GetProperty(propertyName).GetValue(attribute).ToString();

    }

    /// <summary>
    /// Returns a dictionary of all the Enum fields with the string of the property from the custom attribute nulls default to the enumName
    /// </summary>
    public static Dictionary<Enum, string> GetEnumStringReference<TEnum, RAttribute>(string propertyName = "Value")
    {
        Dictionary<Enum, string> _dict = new Dictionary<Enum, string>();
        Type enumType = typeof(TEnum);
        Type enumUnderlyingType = Enum.GetUnderlyingType(enumType);
        Array enumValues = Enum.GetValues(enumType);
        foreach (Enum enumValue in enumValues)
        {
            string enumName = Enum.GetName(typeof(TEnum), enumValue);
            string decoratorValue = Common.GetAttributeValue<RAttribute>(enumValue, propertyName) ?? enumName;
            _dict.Add(enumValue, decoratorValue);
        }

        return _dict;
    }

2
我想出了一种不同的方法来定位目标枚举值的FieldInfo元素。将枚举值转换为字符串进行定位感觉不太对,因此我选择使用LINQ检查字段列表:

我采用了不同的方法来定位目标枚举值的FieldInfo元素。将枚举值转换为字符串进行定位感觉不太对,因此我选择使用LINQ检查字段列表:

Type enumType = value.GetType();
FieldInfo[] fields = enumType.GetFields();
FieldInfo fi = fields.Where(tField =>
    tField.IsLiteral &&
    tField.GetValue(null).Equals(value)
    ).First();

所以,所有的东西都拼凑在一起,我有:

最初的回答:

    public static TAttribute GetAttribute<TAttribute>(this Enum value) 
        where TAttribute : Attribute
    {

        Type enumType = value.GetType();
        FieldInfo[] fields = enumType.GetFields();
        FieldInfo fi = fields.Where(tField =>
            tField.IsLiteral &&
            tField.GetValue(null).Equals(value)
            ).First();

        // If we didn't get, return null
        if (fi == null) return null;

        // We found the element (which we always should in an enum)
        // return the attribute if it exists.
        return (TAttribute)(fi.GetCustomAttribute(typeof(TAttribute)));
    }

这是一个不错的干净通用解决方案。非常好用! - Michael Bray

1
public string GetEnumAttributeValue(Enum enumValue, Type attributeType, string attributePropertyName)
        {
            /* New generic version (GetEnumDescriptionAttribute results can be achieved using this new GetEnumAttribute with a call like (enumValue, typeof(DescriptionAttribute), "Description")
             * Extracts a given attribute value from an enum:
             *
             * Ex:
             * public enum X
             * {
                     [MyAttribute(myProp = "aaaa")]
             *       x1,
             *       x2,
             *       [Description("desc")]
             *       x3
             * }
             *
             * Usage:
             *      GetEnumAttribute(X.x1, typeof(MyAttribute), "myProp") returns "aaaa"
             *      GetEnumAttribute(X.x2, typeof(MyAttribute), "myProp") returns string.Empty
             *      GetEnumAttribute(X.x3, typeof(DescriptionAttribute), "Description") returns "desc"
             */

            var attributeObj = enumValue.GetType()?.GetMember(enumValue.ToString())?.FirstOrDefault()?.GetCustomAttributes(attributeType, false)?.FirstOrDefault();

            if (attributeObj == null)
                return string.Empty;
            else
            {
                try
                {
                    var attributeCastedObj = Convert.ChangeType(attributeObj, attributeType);
                    var attributePropertyValue = attributeType.GetProperty(attributePropertyName)?.GetValue(attributeCastedObj);
                    return attributePropertyValue?.ToString() ?? string.Empty;
                }
                catch (Exception ex)
                {
                    return string.Empty;
                }
            }
        }

0
作为对@George Kargakis答案的回应(因为我是个潜水者,声望不够无法评论):
我刚刚使用了你的方法,只是为了明确起见,我将方法命名为`GetAttributeOrDefault`。
另外,未来的读者们,你可以使用null propagation来避免对结果属性的任何空引用异常和丑陋的空检查,像这样:`day.GetAttribute()?.Name`。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接