• 通过反射获得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,
        }
    }
    
    
  • 相关阅读:
    How Google TestsSoftware
    How Google TestsSoftware
    How Google TestsSoftware
    How Google TestsSoftware
    How Google Tests Software
    月薪3万的程序员都避开了哪些坑
    关于BUG率的计算和它的实际意义的思考
    fastJSON☞JSONParameters☞时区的修改☞时间最后有一个"Z"
    基础知识系列☞C#中数组Array、ArrayList和List三者的区别
    WCF--提示:异常消息为“传入消息的消息格式不应为“Raw”。此操作的消息格式应为 'Xml', 'Json'。
  • 原文地址:https://www.cnblogs.com/AlinaL/p/13156577.html
Copyright © 2020-2023  润新知