zoukankan      html  css  js  c++  java
  • 用户自定义Attribute

    今天学习了C#中的Attribute,略做总结

    1.Attribute的本质

    它的本质是一个类,能够对程序中的元素进行标注(如assembly, class, constructor, delegate, enum, event, field, interface, method, portable executable file module, parameter, property, return value, struct, 或者其他attribute.)

    2.如何编写用户Attribute

    如同编写一个类一样,例如:

    // 用户宠物特征.
    public class AnimalTypeAttribute : Attribute {
    // 构造器.
    public AnimalTypeAttribute(Animal pet) {
    thePet = pet;
    }
    // 内部变量.
    protected Animal thePet;
    // 属性.
    public Animal Pet {
    get { return thePet; }
    set { thePet = value; }
    }
    }


    3.如何使用用户Attribute

    // 对一个测试类的方法添加特征.
    class AnimalTypeTestClass {
    [AnimalType(Animal.Dog)]
    public void DogMethod() {}

    [AnimalType(Animal.Cat)]
    public void CatMethod() {}

    [AnimalType(Animal.Bird)]
    public void BirdMethod() {}
    }

    4.如何让用户Attribute运用内部逻辑

    class DemoClass {
    static void Main(string[] args) {
    AnimalTypeTestClass testClass = new AnimalTypeTestClass();
    Type type = testClass.GetType();
    // 利用反射,遍历这个类中的所有方法 System.Reflection
    foreach(MethodInfo mInfo in type.GetMethods()) {
    // 通过Attribute类内置的GetCustemAttributes()方法遍历附加在该方法上的所有Attribute.
    foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo)) {
    // 定位目标Attribute,进行相应的逻辑操作.
    if (attr.GetType() == typeof(AnimalTypeAttribute))
    Console.WriteLine(
    "Method {0} has a pet {1} attribute.",
    mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
    }
    }
    }
    }
    /*
    * Output:
    * Method DogMethod has a pet Dog attribute.
    * Method CatMethod has a pet Cat attribute.
    * Method BirdMethod has a pet Bird attribute.
    */


    上面这个例子是MSDN官方的例子,很好懂;
    然后附一篇很适合Attribute入门的博客
    最后再附一篇比较完整的例子

  • 相关阅读:
    git刚初始化项目的操作
    git在不同平台windows、linux、mac 上换行符的问题
    HTTP请求报文和HTTP响应报文
    记一次挂马清除经历:处理一个利用thinkphp5远程代码执行漏洞挖矿的木马
    Shell 一键安装命令
    Linux下ThinkPHP网站目录权限设置
    Linux fdisk普通分区扩容
    cachecloud安装部署
    python
    【转】【Python】Python网络编程
  • 原文地址:https://www.cnblogs.com/chenjunsheep/p/1733870.html
Copyright © 2011-2022 走看看