本文导读

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. 转载c#泛型 类型参数的约束(c#编程指南)

    在定义泛型类时,可以对客户端代码能够在实例化类时用于类型参数的类型种类施加限制.如果客户端代码尝试使用某个约束所不允许的类型来实例化类,则会产生编译时错误.这些限制称为约束.约束是使用 where 上 ...

  2. UI进阶 多线程

    一.多线程概述 程序.进程.线程 程序:由源代码生成的可执行应用.(例如:QQ.app) 进程:一个正在运行的程序可以看做一个进程.(例如:正在运行的QQ就是一个进程),进程拥有独立运行所需的全部资源 ...

  3. ajax 返回json数据操作

    例子: $.ajax({ url: "<?=Url::toRoute('add-all-staff')?>", type: 'get', dataType: 'json ...

  4. 虚方法(virtual)和抽象方法(abstract)的区别

    注:本文转载自 http://www.cnblogs.com/michaelxu/archive/2008/04/01/1132633.html 虚方法和抽象方法都可以供派生类重写,它们之间有什么区别 ...

  5. 剑指OFFER之合并有序链表(九度OJ1519)

    题目描述: 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则.(hint: 请务必使用链表.) 输入: 输入可能包含多个测试样例,输入以EOF结束.对于每个测 ...

  6. svn 如何解决冲突

    项目中,往往不止你一人开发,多人开发,难免会有代码的冲突.彼此间谁也不能保证不会修改同个文件.如果修改了同个方法的内容.这时提交到svn是会提示代码冲突的. 当然,冲突是可控的,但不能避免.每次写代码 ...

  7. cocos2d-x Animation

    转自:http://codingnow.cn/cocos2d-x/810.html 这一篇来学习怎么使用cocos2d-x引擎播放帧动画,就是把一帧一帧的图片像电影那样显示出来.1. 首先来了解一下相 ...

  8. ios常用动画

    // // CoreAnimationEffect.h // CoreAnimationEffect // // Created by VincentXue on 13-1-19. // Copyri ...

  9. 教你如何选择Android游戏引擎

    我们进行Android游戏开发时选择游戏引擎是必须的,但是该如何选择呢?哪个Android游戏引擎更加适合自己呢?本文就提供了三个游戏引擎的对比说明,阐述了它们各自的特点,为大家选择引擎提供了参照. ...

  10. json处理复杂对象jsonConfig

     我们通常的Json字符串和java当对象互转.经常有选择性地过滤掉一些属性值,和json-lib包JsonConfig为我们提供了这样一个 特征,有几种方法实施细则. (1)建立JsonConf ...