繁体   English   中英

GetCustomAttribute返回null

[英]GetCustomAttribute returns null

有人可以向我解释为什么Value.GetType().GetCustomAttribute返回null 我查看了十个不同的教程,了解如何获取枚举类型成员的属性。 无论我使用哪种GetCustomAttribute*方法,我都没有返回自定义属性。

using System;
using System.ComponentModel;
using System.Reflection;

public enum Foo
{
    [Bar(Name = "Bar")]
    Baz,
}

[AttributeUsage(AttributeTargets.Field)]
public class BarAttribute : Attribute
{
    public string Name;
}

public static class FooExtensions
{
    public static string Name(this Foo Value)
    {
        return Value.GetType().GetCustomAttribute<BarAttribute>(true).Name;
    }
}

因为您尝试检索的属性尚未应用于该类型; 它已被应用于该领域。

因此,您需要在FieldInfo对象上调用它,而不是在类型对象上调用GetCustomAttributes。 换句话说,你需要做更多这样的事情:

typeof(Foo).GetField(value.ToString()).GetCustomAttributes...

phoog对问题的解释是正确的。 如果您想要一个如何在枚举值上检索属性的示例,请查看此答案

你的属性是在字段级别,而Value.GetType().GetCustomAttribute<BarAttribute>(true).Name将返回应用于枚举Foo的属性

我想你必须像这样重写FooExtension:

public static class FooExtensions
{
    public static string Name(this Foo Value)
    {
        string rv = string.Empty;
        FieldInfo fieldInfo = Value.GetType().GetField(Value.ToString());
        if (fieldInfo != null)
        {
            object[] customAttributes = fieldInfo.GetCustomAttributes(typeof (BarAttribute), true);
            if(customAttributes.Length>0 && customAttributes[0]!=null)
            {
                BarAttribute barAttribute = customAttributes[0] as BarAttribute;
                if (barAttribute != null)
                {
                    rv = barAttribute.Name;
                }
            }
        }

        return rv;
    }
}

我最终重写了这样:

public static class FooExtensions
{
    public static string Name(this Foo Value)
    {
        var Type = Value.GetType();
        var Name = Enum.GetName(Type, Value);
        if (Name == null)
            return null;

        var Field = Type.GetField(Name);
        if (Field == null)
            return null;

        var Attr = Field.GetCustomAttribute<BarAttribute>();
        if (Attr == null)
            return null;

        return Attr.Name;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM