如何反映应用于枚举类型本身的自定义属性

Mic*_*ael 2 c# reflection enums attributes

我有一个自定义属性,我想要应用于枚举类型本身,但我无法确定正确的路径,以获得正确的*信息,以暴露属性.

像这样的东西

[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class MyCustAttribute : Attribute {}
[MyCust()]
[MyCust()]
[MyCust()]/*...and so on...*/
public enum MyEnumType{}
Run Code Online (Sandbox Code Playgroud)

我熟悉从枚举值反映说明DescriptionAttribute的更"习惯"的方法.我一直这样做,没问题.如下面的类型情况.

public enum MyEnumType {
    [Description("My First Value")]
    First,
    [Description("My Second Value")]
    Second,
}
Run Code Online (Sandbox Code Playgroud)

我确信这很明显,但我不知道这是否可行.

Ric*_*key 6

您可以迭代enum这样的类型的自定义属性:

static void Main(string[] args)
{
    var attributes = typeof(MyEnumType).GetCustomAttributes(typeof(MyCustAttribute), false);
    foreach (MyCustAttribute attribute in attributes)
        Console.WriteLine("attribute: {0}", attribute.GetType().Name);
    Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,GetCustomAttributes返回一个数组object.我们使用foreach循环的能力来扩展我们知道数组元素包含的类型,因为这就是我们要求的:MyCustAttribute.

由于您的自定义属性还没有任何有趣的内容,我们只选择打印出该类型的名称.你显然会用你真实的类型实例做一些更令人兴奋的事情.