(1)特性是什么
CLR允许添加类似关键字的描述声明叫做attributes, 它对程序中的目标元素进行标注,如类型、字段、方法和属性等。
Attributes和Microsoft .NET Framework文件的元数据保存在一起,可以用来向运行时描述你的代码或者在程序运行的时候影响应用程序的行为。
总结为:定制特性attribute,本质上是一个类,为目标元素提供关联附加信息并在运行期以反射的方式来获取附加信息。
定制特性可应用的目标元素:程序集(assembly)、模块(module)、类型(type)、属性(property)、事件(event)、字段(field)、方法(method)、参数(param)、返回值(return),其实关于数组来接受任意长度的参数就是用特性来做出来的
几个习惯用法:
自定义特性必须直接或间接继承自System.Attribute类而且该类必须要有公有的构造函数;
自定义特性应该有一个Attribute后缀,习惯约定(在调用中可以省略,会自动匹配);
非抽象特性必须要有public访问权限;
定制特性不会影响应用元素的任何功能,只是约定了该元素具有的特质;
(2)如何自定义特性
定义一个特性的本质就是定义一个继承自System.Attribute类的类型.
/// <summary>
/// 一个自定义特性MyCustomAttribute
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute
{
private string className;
public MyCustomAttribute(string className)
{
this.className = className;
}
// 一个只读属性ClassName
public string ClassName
{
get
{
return className;
}
}
}
[MyCustom("UseMyCustomAttribute")]
class UseMyCustomAttribute
{
static void Main(string[] args)
{
Type t = typeof(UseMyCustomAttribute);
// 通过GetCustomAttributes方法得到自定义特性
object[] attrs = t.GetCustomAttributes(false);
MyCustomAttribute att = attrs[0] as MyCustomAttribute;
Console.WriteLine(att.ClassName);
Console.ReadKey();
}
}
实际项目的例子
namespace SC.Component.Utility
{
using System;
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
public sealed class APIMethodAttribute : Attribute
{
private string m_APIUrl;
public APIMethodAttribute()
{
}
public APIMethodAttribute(string apiUrl)
{
this.m_APIUrl = apiUrl;
}
public string APIUrl
{
get
{
return this.m_APIUrl;
}
set
{
this.m_APIUrl = value;
}
}
}
}
//一个继承自System.Attribute的类型,就是一个自定义特性,并且可以将其添加到适合的元素之上
[APIMethod("TravelOrderList")] public static string GetTravelList(JourneyCalendarParmas reqParams) { string result = string.Empty; try { ........ } catch (Exception ex) { return null; } return result; }
原文:http://www.cnblogs.com/tiantianle/p/5768075.html