• Attribute


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace ReflectionClass
    {
    public enum Fruit
    {
    Apple,
    Banana,
    Pear,
    Watermelon
    }

    public class FruitTypeAttribute:System.Attribute
    {
    public FruitTypeAttribute(Fruit fruit)
    {
    this.fruit = fruit;
    }

    protected Fruit fruit;
    public Fruit TheFruit
    {
    get { return fruit; }
    set { fruit = value; }
    }
    }

    public class FruitTest:IFruit
    {
    [FruitType(Fruit.Apple)]
    public void AppleMethod() { }

    [FruitType(Fruit.Pear)]
    public void PearMethod() { }
    }
    }

    在使用Attribute的时候[FruitType(Fruit.Apple)]实际上就是实现了FruitTypeAttribute的构造方法,而在构造方法中又为TheFruit属性赋值。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;

    namespace ReflectionTest
    {
    class AssemblyTest
    {
    public static Assembly ReflectionClassAssembly
    {
    get
    {
    return Assembly.Load("ReflectionClass");
    }
    }

    public static void ShowAttributeInfo()
    {
    //object fruitTest = ReflectionClassAssembly.CreateInstance("ReflectionClass.FruitTest");
    Type fruitTest = ReflectionClassAssembly.GetType("ReflectionClass.FruitTest");
    MethodInfo method
    = fruitTest.GetMethod("AppleMethod", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);//可省略第二个参数

    Type fruitType
    = ReflectionClassAssembly.GetType("ReflectionClass.FruitTypeAttribute");
    Attribute attr
    = Attribute.GetCustomAttribute(method, fruitType);
    if (attr!=null)
    {
    PropertyInfo property
    = fruitType.GetProperty("TheFruit", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);//可省略第二个参数
    Console.WriteLine("the {0} attribute is : {1}", method.Name, property.GetValue(attr, null));
    }
    //Attribute[] attrs = Attribute.GetCustomAttributes(method);
    //if (attrs.Length > 0)
    //{
    //Console.WriteLine("the {0} attribute is : {1}",method.Name,property.GetValue(attrs[0],null));
    //((ReflectionClass.FruitTypeAttribute)attrs[0]).TheFruit
    //}
    }
    }
    }

  • 相关阅读:
    【数学】【AOJ-614】座位安排
    【乱搞】【AOJ-611】消失的5,8,9
    redis 与session
    Nginx 与 tomcat 部署网站
    linux 进程在后台执行
    印象笔记
    consul 小結
    spring boot 使用拦截器,注解 实现 权限过滤
    Springcloud/Springboot项目绑定域名,使用Nginx配置Https
    spring boot 登录认证
  • 原文地址:https://www.cnblogs.com/xingbinggong/p/2154040.html
Copyright © 2020-2023  润新知