gxc

永远不要认为有什么事情是理所当然的!

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
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();
        }

    }

}
posted on 2006-03-29 14:29  gxc  阅读(175)  评论(0编辑  收藏  举报