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入门的博客
    最后再附一篇比较完整的例子

  • 相关阅读:
    验证字符串空“” 的表达式
    should not this be a private conversation
    【转】你真的了解word-wrap 和 word-break 的区别吗
    To live is to function,that is all there is in living
    [转] windows 上用程序putty使用 ssh自动登录Linux(Ubuntu)
    Vim/gvim容易忘记的快捷键
    [转] Gvim for windows中块选择的方法
    问题集
    web services
    Trouble Shooting
  • 原文地址:https://www.cnblogs.com/chenjunsheep/p/1733870.html
Copyright © 2011-2022 走看看