本文导读

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 (一)的更多相关文章

  1. [C#] 剖析 AssemblyInfo.cs - 了解常用的特性 Attribute

    剖析 AssemblyInfo.cs - 了解常用的特性 Attribute [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/5944391.html 序 ...

  2. JavaScript特性(attribute)、属性(property)和样式(style)

    最近在研读一本巨著<JavaScript忍者秘籍>,里面有一篇文章提到了这3个概念. 书中的源码可以在此下载.我将源码放到了线上,如果不想下载,可以直接访问在线网址,修改页面名就能访问到相 ...

  3. [C#] C# 知识回顾 - 特性 Attribute

    C# 知识回顾 - 特性 Attribute [博主]反骨仔 [原文地址]http://www.cnblogs.com/liqingwen/p/5911289.html 目录 特性简介 使用特性 特性 ...

  4. js attribute 和 jquery attr 方法

    attribute 是原生js dom 对象上的一个属性,这个属性有很多子属性,比如 isId(判断属性是否是Id) , name (获取属性名称) , value (获取属性值),attribute ...

  5. 【.net 深呼吸】自定义特性(Attribute)的实现与检索方法

    在.net的各个语言中,尤其是VB.NET和C#,都有特性这一东东,具体的概念,大家可以网上查,这里老周说一个非标准的概念——特性者,就是对象的附加数据.对象自然可以是类型.类型成员,以及程序集. 说 ...

  6. angular2系列教程(四)Attribute directives

    今天我们要讲的是ng2的Attribute directives.顾名思义,就是操作dom属性的指令.这算是指令的第二课了,因为上节课的components实质也是指令. 例子

  7. 学会给你的类(及成员)来定制一套自己的Attribute吧

    在通过Visual Studio创建的C#程序集中,都包含了一个AssemblyInfo.cs的文件,在这个文件中,我们常常会看到这样的代码 [assembly: AssemblyTitle(&quo ...

  8. Attribute操作的性能优化方式

    Attribute是.NET平台上提供的一种元编程能力,可以通过标记的方式来修饰各种成员.无论是组件设计,语言之间互通,还是最普通的框架使 用,现在已经都离不开Attribute了.迫于Attribu ...

  9. SharePoint 2016 配置向导报错 - The 'ListInternal' attribute is not allowed

    前言 配置SharePoint 2016的配置向导中,第三步创建配置数据库报错,然后百度.谷歌了一下,都没有解决,自己看日志搞定,也许会有人遇到类似问题,分享一下. 1.配置向导的错误截图,如下图: ...

  10. C# 知识特性 Attribute

    C#知识--获取特性 Attribute 特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集.类型.方法.属性等)相关联.特性与程序实体关联后,可在运行时使用"反射"查询 ...

随机推荐

  1. IPO

    Initial Public Offerings,简称IPO,首次公开募股(Initial Public Offerings,简称IPO):是指一家企业或公司 [1] (股份有限公司)第一次将它的股份 ...

  2. 低级错误之Hbm中类型不一致错误

    Myeclipse将数据库中的长整形生成为Bigdecimal类型,实际应该生成为Long.导致保存的时候报错.

  3. iOS 分类和继承

    iOS 中分类(Categories) 和 继承(Inherit)有相同的功能,但在一些细节上又有差异,简单介绍一下两者的异同. 分类可以在不知道系统类源代码的情况下,为这个类添加新的方法.分类只能用 ...

  4. JavaScript 要点(十六)RegExp 对象

    RegExp:是正则表达式(regular expression)的简写. RegExp 对象 正则表达式是描述字符模式的对象. 正则表达式用于对字符串模式匹配及检索替换,是对字符串执行模式匹配的强大 ...

  5. Young不等式的一个新证明

    设 $p>0,q>0,a>0,b>0$ 且 $1/p+1/q=1$ 有 \[ab\leq \frac{a^{p}}{p}+\frac{b^{q}}{q}\] 证明:设 \[f( ...

  6. c/c++中使用指针需要注意的问题

    一.使用指针的时候需要注意几点: 分配空间 初始化 释放 二.常见的错误有几种: 1)内存分配未成功,却使用了它      编程新手常犯这种错误,因为他们没有意识到内存分配会不成功.常用解决办法是,使 ...

  7. ThinkPHP CURD方法盘点:field方法

    ThinkPHP的CURD操作中有很多非常实用的方法,从这篇开始,我们会为大家一一介绍. 首先为大家介绍下field方法的用法.field属于模型的连贯操作方法之一,主要目的是标识要返回或者操作的字段 ...

  8. Windows内核之进程基本含义以及进程的创建

    进程 1 进程的含义: 1.1   一个是操作系统用来管理进程的内核对象. 内核对象也是系统用来存放关于进程的统计信息的地方. 1.2   还有一个是地址空间,它包括全部可运行模块或DL L 模块的代 ...

  9. Linux SO_KEEPALIVE属性,心跳

    对于面向连接的TCP socket,在实际应用中通常都要检測对端是否处于连接中,连接port分两种情况: 1.连接正常关闭,调用close() shutdown()连接优雅关闭,send与recv立刻 ...

  10. Ubuntu10.04下载并编译Android4.3源代码

    注:转载或引用请标明出处    http://blog.csdn.net/luzhenrong45/article/details/9719433 去年用Ubuntu10.10成功下载并编译Andro ...