首页 > 其他 > 详细

通过反射获得Attribute

时间:2020-06-18 11:30:30      阅读:68      评论:0      收藏:0      [点我收藏+]
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,
??? }
}

通过反射获得Attribute

原文:https://www.cnblogs.com/AlinaL/p/13156577.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!