本文导读

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. 一步一步学数据结构之n--n(图遍历--深度优先遍历--非递归实现)

    前面已经说了图的深度优先遍历算法,是用递归实现的,而在这里就讲一下用非递归实现,需要借助栈: 算法思想:        1. 栈初始化        2. 输出起始顶点,起始顶点改为“已访问”标志,将 ...

  2. Jquery ajax 得到返回值

    Jquery ajax 得到返回值 1.ajax默认是异步调用的,所以得到的返回值是空值,要得到值必须改成同步:async: false,//同步. 2.必须定义一个全局变量 var result = ...

  3. Egret的第一个2048游戏

    http://bbs.egret-labs.org/thread-242-1-1.html 对于AS3的开发者来说,可以直接过渡到的HTML5框架就是Egret了,基本上是了解了TypeSprite的 ...

  4. Spring Framework 5.0.0.M3中文文档 翻译记录 Part I. Spring框架概览1-2.2

    Part I. Spring框架概览 The Spring Framework is a lightweight solution and a potential one-stop-shop for ...

  5. 导出cluster log

    将所有群集节点的日志导出到 clog 目录下: get-clusterlog -destination c:\clog 只导出前10分钟的群集日志: get-cluster -destination ...

  6. [置顶] MySQL Cluster初步学习资料整理--安装部署新特性性能测试等

    1.1 mysql-cluster简介 简单的说,MySQLCluster实际上是在无共享存储设备的情况下实现的一种完全分布式数据库系统,其主要通过NDBCluster(简称NDB)存储引擎来实现. ...

  7. iOS开发——UI篇OC篇&UIDynamic详解

    iOS开发拓展篇—UIDynamic(简单介绍) 一.简单介绍 1.什么是UIDynamic UIDynamic是从iOS 7开始引入的一种新技术,隶属于UIKit框架 可以认为是一种物理引擎,能模拟 ...

  8. Unescape HTML entities in Javascript Unescape HTML转成html代码

    前言: 在javascript里面动态创建标准dom对象一般使用: var obj = document.createElement('div'); 然后再给obj设置一些属性. 但是,在实际使用过程 ...

  9. Top 10 Algorithms for Coding Interview--reference

    By X Wang Update History:Web Version latest update: 4/6/2014PDF Version latest update: 1/16/2014 The ...

  10. C# 之 日常积累(二)

    主要涉及(1)数字前补0:(2)去掉decimal类型后边无效的0相关问题. 1.数字前补0 ; ) { returnnumber.ToString(); } else { returnnumber. ...