zoukankan      html  css  js  c++  java
  • Attribute Example In MSDN

    using System;
    using System.Reflection;

    namespace CustomAttrCS {
        
    // An enumeration of animals. Start at 1 (0 = uninitialized).
        public enum Animal {
            
    // Pets.
            Dog = 1,
            Cat,
            Bird,
        }


        
    // A custom attribute to allow a target to have a pet.
        public class AnimalTypeAttribute : Attribute {
            
    // The constructor is called when the attribute is set.
            public AnimalTypeAttribute(Animal pet) {
                thePet 
    = pet;
            }


            
    // Keep a variable internally 
            protected Animal thePet;

            
    // .. and show a copy to the outside world.
            public Animal Pet {
                
    get return thePet; }
                
    set { 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();
                
    // Iterate through all the methods of the class.
                foreach(MethodInfo mInfo in type.GetMethods()) {
                    
    // Iterate through all the Attributes for each method.
                    foreach (Attribute attr in 
                        Attribute.GetCustomAttributes(mInfo)) 
    {
                        
    // Check for the AnimalType attribute.
                        if (attr.GetType() == typeof(AnimalTypeAttribute))
                            Console.WriteLine(
                                
    "Method {0} has a pet {1} attribute."
                                mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
                    }


                }

            }

        }

    }


    /*
     * Output:
     * Method DogMethod has a pet Dog attribute.
     * Method CatMethod has a pet Cat attribute.
     * Method BirdMethod has a pet Bird attribute.
     
    */
  • 相关阅读:
    Nginx+PHP-FPM优化技巧总结
    基于php-fpm的配置详解
    Nginx中修改php.ini的上传设置upload_max_filesize的值
    nginx调用php-fpm出错解决方法和nginx配置详解
    LNMP笔记:php-fpm – 启动参数及重要配置详解
    nginx php-fpm安装手记
    C#使用Log4Net记录日志
    .NET中使用Redis (二)
    .NET中使用Redis
    SQL自定义函数split分隔字符串
  • 原文地址:https://www.cnblogs.com/EasyLive2006/p/625584.html
Copyright © 2011-2022 走看看