【发布时间】:2012-12-26 11:14:08
【问题描述】:
谁能向我解释为什么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;
}
}
【问题讨论】:
-
也许我应该改写我的问题。我明白为什么会抛出
NullReferenceException。我不明白为什么Value.GetType().GetCustomAttribute返回null。
标签: c# enums custom-attributes