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

  • 相关阅读:
    关于Delphi中RS Float字段只有4位及OADateTime不能显示到秒的解决办法
    xml特殊字符处理(js)
    总结一下最近将163邮箱拖动效果改成兼容Firefox遇到的问题
    在XIB里面关于@property,@synthesize,release,dealloc的怪现象
    关于Core Data里面删除了一个被retain的NSManagedObject
    Hello cnblogs' world!
    html5离线应用程序 Amy
    css3布局相关的样式 Amy
    html5拖放API Amy
    css3MediaQueries的相关样式 Amy
  • 原文地址:https://www.cnblogs.com/chenjunsheep/p/1733870.html
Copyright © 2011-2022 走看看