using System;
using System.Reflection;
namespace CustomAttrCS
{
public enum Animal{Dog = 1,Cat,Bird,}
public class AnimalTypeAttribute : Attribute
{
protected Animal thePet;
public Animal Pet
{
get { return thePet; }
set { thePet = Pet; }
}
public AnimalTypeAttribute(Animal pet)
{
thePet = pet;
}
}
// A test class where each method has its own pet.
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();
Console.WriteLine(type.ToString());
//循环type的所有方法
foreach (MethodInfo mInfo in type.GetMethods())
{
int i = 0;
Console.WriteLine("_____"+mInfo.ToString());
//循环每个方法的标签
foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
{
i++;
Console.WriteLine("11111111" + attr.ToString()+"******"+i.ToString());
if (attr.GetType() == typeof(AnimalTypeAttribute))
Console.WriteLine("Method {0} has a pet {1} attribute.",mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
}
}
Console.Read();
}
}
}
using System.Reflection;
namespace CustomAttrCS
{
public enum Animal{Dog = 1,Cat,Bird,}
public class AnimalTypeAttribute : Attribute
{
protected Animal thePet;
public Animal Pet
{
get { return thePet; }
set { thePet = Pet; }
}
public AnimalTypeAttribute(Animal pet)
{
thePet = pet;
}
}
// A test class where each method has its own pet.
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();
Console.WriteLine(type.ToString());
//循环type的所有方法
foreach (MethodInfo mInfo in type.GetMethods())
{
int i = 0;
Console.WriteLine("_____"+mInfo.ToString());
//循环每个方法的标签
foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
{
i++;
Console.WriteLine("11111111" + attr.ToString()+"******"+i.ToString());
if (attr.GetType() == typeof(AnimalTypeAttribute))
Console.WriteLine("Method {0} has a pet {1} attribute.",mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
}
}
Console.Read();
}
}
}