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,
        }
    }
    
    
  • 相关阅读:
    阅读书籍推荐
    lvarchar类型对表结构变更影响
    离职总结 | 如何做个好员工?
    Windows7 general operation/cmd notes
    (转)CONST用法
    Linux多线程的使用一:互斥锁
    hadoop2.5.2学习及实践笔记(六)—— Hadoop文件系统及其java接口
    hadoop2.5.2学习及实践笔记(五)—— HDFS shell命令行常见操作
    hadoop2.5.2学习及实践笔记(四)—— namenode启动过程源码概览
    hadoop2.5.2学习及实践笔记(三)—— HDFS概念及体系结构
  • 原文地址:https://www.cnblogs.com/AlinaL/p/13156577.html
Copyright © 2011-2022 走看看