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,
        }
    }
    
    
  • 相关阅读:
    MySQL 8.0.14版本新功能详解
    Uncaught TypeError: Right-hand side of 'instanceof' is not an object
    程序员快速技术提升之道
    Windows 10 cmd命令符的使用
    数据千万条,备份第一条:VFEmail被擦除所有数据面临关停
    netty-socketio 示例代码
    idea中 在接口中如何直接跳转到该接口的是实现类中?
    perl DBD处理超时问题
    springboot 启动配置文件配置
    Office Word 发布文章到博客园
  • 原文地址:https://www.cnblogs.com/AlinaL/p/13156577.html
Copyright © 2011-2022 走看看