Represents the base class for custom attributes.
using System;
using System.Reflection;
public enum Animal {
Dog = 1,
Cat,
Bird,
}
public class AnimalTypeAttribute : Attribute {
public AnimalTypeAttribute(Animal pet) {
thePet = pet;
}
protected Animal thePet;
public Animal Pet {
get { return thePet; }
set { thePet = value; }
}
}
class AnimalTypeTestClass {
[AnimalType(Animal.Dog)]
public void DogMethod() {}
[AnimalType(Animal.Cat)]
public void CatMethod() {}
[AnimalType(Animal.Bird)]
public void BirdMethod() {}
}
class DemoClass {
static void Main(string[] args) {
AnimalTypeTestClass testClass = new AnimalTypeTestClass();
Type type = testClass.GetType();
foreach(MethodInfo mInfo in type.GetMethods()) {
foreach (Attribute attr in
Attribute.GetCustomAttributes(mInfo)) {
if (attr.GetType() == typeof(AnimalTypeAttribute))
Console.WriteLine(mInfo.Name);
Console.WriteLine(((AnimalTypeAttribute)attr).Pet);
}
}
}
}
Related examples in the same category