For a long time I was sure it is not supported, because there was no corresponding AttributeTargets value.
It turns out, that you can do it by using AttributeTargets.Field
. Declaring your attribute class:
[AttributeUsage(AttributeTargets.Field)]
public class CategoryAttribute : Attribute
Declaring your decorated enum:
enum MyEnum
{
[Category("foo")]
Foo,
[Category("This is bar")]
Bar,
Baz
}
Reading attribute values:
foreach (MyEnum x in Enum.GetValues(typeof(MyEnum)))
{
MemberInfo[] info = typeof(MyEnum).GetMember(x.ToString());
if (info.Length != 1)
{
Console.WriteLine("Get {0} members for {1}", info.Length, x);
continue;
}
Attribute[] categories = Attribute.GetCustomAttributes(info[0], typeof(CategoryAttribute));
if (categories.Length == 0)
{
Console.WriteLine("{0}: No category", x);
}
else
{
CategoryAttribute category = (CategoryAttribute)categories[0];
Console.WriteLine("{0}: {1}", x, category.Category);
}
}