zoukankan      html  css  js  c++  java
  • 通过反射获得Attribute

    建议打断点食用

    using System;
    
    using System.Reflection;
    
    
    
    namespace ConsoleApp
    {
        class Program
        {
            static void Main(string[] args)
            {
            
                AnimalTypeModel testClass = new AnimalTypeModel();
    
                Type type = testClass.GetType();
    
                foreach (MethodInfo mInfo in type.GetMethods())
                {
                    var ca = Attribute.GetCustomAttributes(mInfo);
    
                    CNNameAttribute thisAttr = ca[1] as CNNameAttribute;
    
                    if (thisAttr.Name == "狗")
                    {
                       Console.WriteLine(thisAttr.Name);
                    }
                    else
                    {
                        Console.WriteLine("不是狗");
                    }
                }
            }
        }
        
        public class AnimalTypeAttribute : Attribute
        {
    
            public AnimalTypeAttribute(Animal pet)
            {
                thePet = pet;
            }
    
            protected Animal thePet;
    
            public Animal Pet
            {
                get { return thePet; }
                set { thePet = value; }
            }
        }
    
    
    
        /// <summary>
        /// 中文名字
        /// </summary>
        public class CNNameAttribute : Attribute
        {
            public string Name { get; set; }
        }
    
        class AnimalTypeModel
        {
            [AnimalType(Animal.Dog), CNName( Name = "狗")]
            public void DogMethod() { }
    
            [AnimalType(Animal.Cat), CNName(Name = "猫")]
            public void CatMethod() { }
    
            [AnimalType(Animal.Bird), CNName(Name = "鸟")]
            public void BirdMethod() { }
        }
    
    
        public enum Animal
        {
            // Pets.
            Dog = 1,
            Cat,
            Bird,
        }
    }
    
    
  • 相关阅读:
    BZOJ2705: [SDOI2012]Longge的问题 欧拉函数
    BZOJ3884: 上帝与集合的正确用法 拓展欧拉定理
    BZOJ1296: [SCOI2009]粉刷匠 DP
    BZOJ5293: [Bjoi2018]求和 树上差分
    BZOJ1398: Vijos1382寻找主人 Necklace 字符串最小表示法
    BZOJ5189: [Usaco2018 Jan]Cow at Large 贪心+LCA
    BZOJ2654: tree 二分答案+最小生成树
    BZOJ1304: [CQOI2009]叶子的染色 树形dp
    BZOJ1632: [Usaco2007 Feb]Lilypad Pond SPFA+最短路计数
    BZOJ1726: [Usaco2006 Nov]Roadblocks第二短路 K短路
  • 原文地址:https://www.cnblogs.com/AlinaL/p/13156577.html
Copyright © 2011-2022 走看看