您的位置:首页 > 其它

.net 自定义attribute使用

2016-04-16 18:49 211 查看
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为空
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: