GetCustomAttribute返回null

Tyl*_*ton 3 c# enums custom-attributes

有人可以向我解释为什么要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;
    }
}
Run Code Online (Sandbox Code Playgroud)

pho*_*oog 12

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

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

typeof(Foo).GetField(value.ToString()).GetCustomAttributes...
Run Code Online (Sandbox Code Playgroud)

  • 您已将该属性应用于该领域 (2认同)