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

C# 如何反映应用于枚举类型本身的自定义属性,c#,reflection,attributes,enums,C#,Reflection,Attributes,Enums,我有一个自定义属性,我想将其应用于枚举类型本身,但我很难确定获取适当*信息的正确路径以公开该属性 像这样的 [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)] public class MyCustAttribute : Attribute {} [MyCust()] [MyCust()] [MyCust()]/*...and so on...*/ public enum MyEnumTyp

我有一个自定义属性,我想将其应用于枚举类型本身,但我很难确定获取适当*信息的正确路径以公开该属性

像这样的

[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class MyCustAttribute : Attribute {}
[MyCust()]
[MyCust()]
[MyCust()]/*...and so on...*/
public enum MyEnumType{}
我熟悉从枚举值反映DescriptionAttribute的更“习惯”的方法。我总是做那种事,没问题。如以下类型的情况

public enum MyEnumType {
    [Description("My First Value")]
    First,
    [Description("My Second Value")]
    Second,
}

我确信这是显而易见的,但我看不出这是否可行。

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

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();
}
在本例中,
GetCustomAttributes
返回
对象的数组。我们使用
foreach
循环的能力来转换为我们知道的数组元素包含的类型,因为这就是我们所要求的:
mycusttribute

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