zoukankan      html  css  js  c++  java
  • 特性(Attributes)

    定义:特性本质上就是有一种类,通过添加特性,就可以实例化这个特性类;

    我们主要讲一下如何自定义特性,定义的方式和普通的类定义方式一致,但是,
    第一:需要继承标准特性类
    第二:需要添加标准特性,用来限制特性的使用范围等
    第三:必须要定义构造函数,即使是空的
    如下:

    [AttributeUsage(AttributeTargets.All,AllowMultiple = true, Inherited=true)]  //基于标准特性
    class CustomAttr:Attribute                                                   //继承标准特性类
    {
        //0参数构造函数
        public CustomAttr()
        {
     
        }
     

    使用特性例子如下:(这里相当于实例化了2个类

    [CustomAttr(name ="dj",sore=100,message ="222")]
    [CustomAttr(name = "sq", sore = 100, message = "666")]
    class Test
    {
     
    }

    注意:

    [CustomAttr(name ="dj",sore=100,message ="222")],  这里相当于调用了不带任何参数的构造函数,但是使用属性功能进行赋值

    [CustomAttr("dj,100,"666")],                                              这里相当于直接调用了带有三个参数的构造函数

    这就是为什么我们必须要给自定义特性类添加构造函数的原因

    特性的反射

    static void Main(string[] args)
    {
        System.Reflection.MemberInfo info = typeof(Test);
        var customAttrLsit = Attribute.GetCustomAttributes(info, typeof(CustomAttr)) as CustomAttr[];
        for (int i = 0; i < customAttrLsit.Count(); i++)
        {
            Console.WriteLine("================================================");
            Console.WriteLine("创建人:{0}", customAttrLsit[i].name);
            Console.WriteLine("创建时间:{0}", customAttrLsit[i].sore);
            Console.WriteLine("备注消息:{0}", customAttrLsit[i].message);
        }
        Console.ReadKey();
    }
  • 相关阅读:
    linux seqlock 锁
    linux 位操作
    linux 原子变量
    linux 读者/写者自旋锁
    linux自旋锁函数
    linux 自旋锁 API 简介
    linux Completions 机制
    linux 读者/写者旗标
    linux 在 scull 中使用旗标
    Linux 旗标实现
  • 原文地址:https://www.cnblogs.com/sylone/p/6101919.html
Copyright © 2011-2022 走看看