Attribute (一)
本文导读
1、概念
2、自定义一个 Attribute
概念
Attribute是一个特殊的类,我们知道 .NET 程序集 具有自描述的特性(由于元数据),Attribute和.NET的元数据一起,可用来向描述你的代码,或者在程序运行的时候影响应用程序的行为。
和Attribute 密切相关的技术是反射
在.NET 框架中有许多内置的 Attribute,如序列化、安全性、DllImport等
看一个内置Attribute 的代码
using System; static class App
{
static void Main()
{
Lib l = new Lib();
l.Fct();
}
} class Lib
{
[Obsolete]
public void Fct(){}
}
结果

自定义一个 Attribute
系统的Attribute我们不能修改,我们能做的是自定义Attribute。步骤如下:
1、写一个继承 System.Attribute 的类,类名是以 Attribute 结尾
2、用系统自带的AttributeUsage 设置 Attribute
AttributeUsage 中有三个成员我们需要关注 AttributeTargets、AllowMultiple 、Inherited 分别的表示 Attribute 的作用范围、是否允许多个 Attribute实例(Attribute是类,反射时创建实例)、是否允许继承
我们看例子
Inherited 的例子
目录结构

是否允许继承文件夹中有4个文件分别是 Attr.cs(自定义Attribute)、TestLib.cs(Attribute修饰的测试类)、App.cs(第三方验证程序,比如框架)、build.bat 编译命令
看代码
//Attr.cs
using System; namespace XXX.Common.Attr
{
// 不允许属性继承
[AttributeUsage(AttributeTargets.Class,Inherited = false)]
public class AAttribute : Attribute {} // 允许属性继承
[AttributeUsage(AttributeTargets.Class,Inherited = true)]
public class BAttribute : Attribute {}
} //---------------------------------------------------------
// TestLib.cs
using System;
using XXX.Common.Attr; namespace XXX.Common.Lib
{
[A]
[B]
public class BaseLib {} public class ExtendLib : BaseLib {}
} //---------------------------------------------------------
// App.cs
using System;
using XXX.Common.Attr;
using XXX.Common.Lib;
using System.Reflection; namespace XXX.Common.App
{
static class App
{
static void Main()
{
ShowBase();
Console.WriteLine("-----------------");
ShowExtend();
} static void ShowBase()
{
ShowHelper(typeof(BaseLib));
} static void ShowExtend()
{
ShowHelper(typeof(ExtendLib));
} static void ShowHelper(MemberInfo mi)
{
AAttribute a = Attribute.GetCustomAttribute(mi,typeof(AAttribute)) as AAttribute;
BAttribute b = Attribute.GetCustomAttribute(mi,typeof(BAttribute)) as BAttribute; Console.WriteLine(a==null ? "没有AAttribute信息" : "有AAttribute信息");
Console.WriteLine(b==null ? "没有BAttribute信息" : "有BAttribute信息");
}
}
}
build.bat 内容
csc /t:library Attr.cs
csc /t:library /r:Attr.dll TestLib.cs
csc /r:Attr.dll,TestLib.dll App.cs
运行结果:

AllowMultiple 允许重复 Attribute
看代码
// Attr.cs
using System; namespace XXX.Common.Attr
{
// 默认AllowMultiple 为false
[AttributeUsage(AttributeTargets.Class)]
public class AAttribute : Attribute {} [AttributeUsage(AttributeTargets.Class,AllowMultiple=true)]
public class BAttribute : Attribute {}
} //-----------------------------------
// TestLib.cs
using System;
using XXX.Common.Attr; namespace XXX.Common.Lib
{
[A]
[A]
public class Lib1{} [B]
[B]
public class Lib2{}
}
综合例子
//Attr.cs
using System; namespace XXX.Common.Attr
{
[AttributeUsage(AttributeTargets.All)]
public class HelperAttribute : Attribute
{
private string _url;
private string _topic; public HelperAttribute(string url)
{
this._url = url;
} public string Url
{
get {return this._url;}
}
public string Topic
{
get {return this._topic;}
set {this._topic = value;}
}
}
} //---------------------------------------
// TestLib.cs
using System;
using XXX.Common.Attr; namespace XXX.Common.Lib
{
[Helper("http://cnblogs.com/Aphasia")]
public class TestLib
{
[Helper("http://cnblogs.com/Aphasia",Topic="阿飞的博客")]
public void ShowBlog(){}
}
} //-----------------------------------------
// App.cs
using System;
using System.Reflection;
using XXX.Common.Lib;
using XXX.Common.Attr; namespace XXX.Common.Application
{
static class App
{
static void Main()
{
ShowHelp(typeof(TestLib));
ShowHelp(typeof(TestLib).GetMethod("ShowBlog"));
} static void ShowHelp(MemberInfo mi)
{
HelperAttribute attr = Attribute.GetCustomAttribute(mi,typeof(HelperAttribute)) as HelperAttribute; if(attr == null) {Console.WriteLine("No Help for {0}.",mi);}
else
{
Console.WriteLine("Help for {0}:",mi);
Console.WriteLine(" Url={0},Topic={1}",attr.Url,attr.Topic);
}
}
}
}
运行结果

第二篇预告
Attribute (二) 将谈Attribute在设计中的用途,拦截器、Builder 模式
本文完
Attribute (一)的更多相关文章
- [C#] 剖析 AssemblyInfo.cs - 了解常用的特性 Attribute
剖析 AssemblyInfo.cs - 了解常用的特性 Attribute [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/5944391.html 序 ...
- JavaScript特性(attribute)、属性(property)和样式(style)
最近在研读一本巨著<JavaScript忍者秘籍>,里面有一篇文章提到了这3个概念. 书中的源码可以在此下载.我将源码放到了线上,如果不想下载,可以直接访问在线网址,修改页面名就能访问到相 ...
- [C#] C# 知识回顾 - 特性 Attribute
C# 知识回顾 - 特性 Attribute [博主]反骨仔 [原文地址]http://www.cnblogs.com/liqingwen/p/5911289.html 目录 特性简介 使用特性 特性 ...
- js attribute 和 jquery attr 方法
attribute 是原生js dom 对象上的一个属性,这个属性有很多子属性,比如 isId(判断属性是否是Id) , name (获取属性名称) , value (获取属性值),attribute ...
- 【.net 深呼吸】自定义特性(Attribute)的实现与检索方法
在.net的各个语言中,尤其是VB.NET和C#,都有特性这一东东,具体的概念,大家可以网上查,这里老周说一个非标准的概念——特性者,就是对象的附加数据.对象自然可以是类型.类型成员,以及程序集. 说 ...
- angular2系列教程(四)Attribute directives
今天我们要讲的是ng2的Attribute directives.顾名思义,就是操作dom属性的指令.这算是指令的第二课了,因为上节课的components实质也是指令. 例子
- 学会给你的类(及成员)来定制一套自己的Attribute吧
在通过Visual Studio创建的C#程序集中,都包含了一个AssemblyInfo.cs的文件,在这个文件中,我们常常会看到这样的代码 [assembly: AssemblyTitle(&quo ...
- Attribute操作的性能优化方式
Attribute是.NET平台上提供的一种元编程能力,可以通过标记的方式来修饰各种成员.无论是组件设计,语言之间互通,还是最普通的框架使 用,现在已经都离不开Attribute了.迫于Attribu ...
- SharePoint 2016 配置向导报错 - The 'ListInternal' attribute is not allowed
前言 配置SharePoint 2016的配置向导中,第三步创建配置数据库报错,然后百度.谷歌了一下,都没有解决,自己看日志搞定,也许会有人遇到类似问题,分享一下. 1.配置向导的错误截图,如下图: ...
- C# 知识特性 Attribute
C#知识--获取特性 Attribute 特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集.类型.方法.属性等)相关联.特性与程序实体关联后,可在运行时使用"反射"查询 ...
随机推荐
- ST-Link STVP Cannot communicate with the device!
用STLink在ST Visual Programmer中对STM8下载二进制文件有时会出现: 原因:多半是STM8目标板没有电源有问题,或是电源引脚虚焊:
- 5-17 Hashing (25分)
The task of this problem is simple: insert a sequence of distinct positive integers into a hash tabl ...
- linux快速入门 1.1命令行操作
http://lovesoo.org/linux-command-line-operation.html 1.1命令行操作 目录: <wp_nokeywordlink>Shell简介 &l ...
- 【25】考虑写出一个不抛异常的swap函数
1.swap交换对象值,std提供了实现方法模版的实现,它的实现是交换对象值. namespace std { template<typename T> void swap(T& ...
- Project Management - 3) Manage Your Meetings
1. 取消没有价值的会议 会议是有代价和成本的 不要举行顺序式的多人进度报告会议 eg: 这周做了什么,下周还要做什么? 除了发言人和项目经理外,每个人都会觉得无聊. 这种会议是在拖项目的后腿,赶紧停 ...
- js 如何把JSON格式的字符串转换为JSON对象
直接用eval函数.例:var str1 = '{ "url": "www.51qdq.com", "name": "js&quo ...
- Codeforces Round #325 (Div. 2) B. Laurenty and Shop 前缀和
B. Laurenty and Shop Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/586/p ...
- C#_MVC_Repository_CRUD_Model
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace iFlytekDemo ...
- codereview介绍
1. 定义: Code review is systematic examination (often known as peer review) of computer source code. I ...
- 不规则三角网(TIN)(转)
来自:http://blog.csdn.net/kikitamoon/article/details/8217641 Ⅰ 数字高程模型(DEM) 地球表面高低起伏,呈现一种连续变化的曲面,这种曲面无法 ...