Reputation: 21
I've got a custom attribute that I want to apply to an enum type itself, but I'm having trouble identifying the correct path to get at the proper *Info in order to expose the attribute.
Something like this
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class MyCustAttribute : Attribute {}
[MyCust()]
[MyCust()]
[MyCust()]/*...and so on...*/
public enum MyEnumType{}
I am familiar with the more "customary" methods of reflecting say a DescriptionAttribute from an enumerated value. I do that sort of thing all the time, no problem. As in the following type case.
public enum MyEnumType {
[Description("My First Value")]
First,
[Description("My Second Value")]
Second,
}
I'm sure it's obvious, but I fail to see whether this is possible.
Upvotes: 2
Views: 1080
Reputation: 34250
You can iterate over your custom attributes of an enum
type like this:
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();
}
In this example, GetCustomAttributes
returns an array of object
. We use the ability of a foreach
loop to cast up to the type we know the array elements contain because that's what we asked for: MyCustAttribute
.
Since your custom attribute doesn't have anything interesting in it yet, we just chose to print out the name of the type. You'll obviously do something more exciting with your real instance of the type.
Upvotes: 6