using System; using System.Reflection; namespace CustomAttrCS { publicenum Animal{Dog =1,Cat,Bird,} publicclass 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)] publicvoid DogMethod() { } [AnimalType(Animal.Cat)] publicvoid CatMethod() { } [AnimalType(Animal.Bird)] publicvoid BirdMethod() { } } class DemoClass { staticvoid 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(); } } }
posted on
2006-03-29 14:29gxc
阅读(176)
评论(0)
编辑收藏举报