zoukankan      html  css  js  c++  java
  • 下面的代码示例演示 Attribute 的用法。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;

    namespace ConsoleApplication1
    {
    //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 attirbute is set
    public AnimalTypeAttribute(Animal pet)
    {
    thePet = pet;
    }
    //Keep a variable internally...
    protected Animal thePet;

    //..and show a copy to outside world.
    public Animal Pet {
    get { return thePet; }
    set { thePet = value; }
    }
    }

    //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 class
    foreach (MethodInfo mInfo in type.GetMethods()) //mInfo=Void DogMethod()
    {


    //Iterate through all the Attributes for each method
    foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))//attr=ConsoleApplication1.AnimalTypeAttribute
    {

    //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.
    */
    }

    }
    }
    Console.ReadKey();
    }

    }
    }

  • 相关阅读:
    硬件加速 Hardware Accelerated [MD]
    Redis 常见面试题(2020最新版)
    1秒时限情况下算法复杂度要求
    linux ikatago-server
    Linux踢出其他正在SSH登陆用户
    多个Git帐号的SSH key切换(不同网站的gitlab&github)
    RTL8201 替换适配国产JL11网卡
    网卡PHY 移植注意事项
    django shell执行命令来批量更新model 数据
    git 设置和取消socks5 代理
  • 原文地址:https://www.cnblogs.com/netmvc8/p/3515037.html
Copyright © 2011-2022 走看看