.net 自定义attribute使用

来源:互联网 发布:php入门经典 pdf 编辑:程序博客网 时间:2024/06/05 02:58

1.简介

公共语言运行时允许你添加类似关键字的描述声明,叫做attributes,

它对程序中的元素进行标注,如类型、字段、方法和属性等。

Attributes和Microsoft .NET Framework文件的元数据保存在一起,可以用来向运行时描述你的代码,或者在程序运行的时候影响应用程序的行为

2.用途(自己积累)

标识字段是否参与插入操作

3.实例

//应用到程序的什么地方,AttributeTargets.Property 属性,即属性上(?)

//AttributeTargets.Class 作用到类上

[AttributeUsage(AttributeTargets.Property)]

//需要继承Attribute,而且命名要以Attribute结尾,使用的时候不用连带Attribute

    public class OperationFlagAttribute : Attribute
    {
        private bool canOperate;

        public bool CanOperate { get { return canOperate; } }
        public OperationFlagAttribute(bool flag)
        {
            canOperate=flag;
        }
    }


4.使用

  private string title;
        [OperationFlag(true)] // 标识到字段属性上
        public string Title
        {
            get { return title; }
            set { title = value; }
        }


5.获取

object[] o = prolist[i].GetCustomAttributes(typeof(OperationFlagAttribute), false);//需要注意的是如果属性没有定义attribute则o为空

0 0
原创粉丝点击