1.Attribute定义
// 长记法
[ConditionalAttribute("LI")]
[ConditionalAttribute("NoBug")]
publicstaticvoidFun()
{Console.WriteLine("Created By Li, NoBug.");}
// 短记法
[Conditional("LI")]
[Conditional("NoBug")]
publicstaticvoidFun()
{Console.WriteLine("Created By Li, NoBug.");}
就像牡蛎天生就要吸附在礁石或船底上一样,Attribute 的实例一构造出来就必需“粘”在一个什么目标上。
Attribute 实例化的语法是相当怪异的,主要体现在以下三点:
1. 不使用new 操作符来产生实例,而是使用在方括号里调用构造函数来产生实例。
2. 方括号必需紧挨着放置在被附着目标的前面。
3. 因为方括号里空间有限,不能像使用new 那样先构造对象,然后再给对象的属性(Property)赋值。
因此,对Attribute 实例的属性赋值也在构造函数的圆括号里。
并且,Attribute 实例化时尤其要注意的是:
1. 构造函数的参数是一定要写。有几个就得写几个,因为你不写的话实例就无法构造出来。
2. 构造函数参数的顺序不能错。调用任何函数都不能改变参数的顺序,除非它有相应的重载(Overload)。因为这个顺序是固定的,有些书里称其为“定位参数”(意即“个数和位置固定的参数”)。
3. 对Attribute 实例的属性的赋值可有可无。反正它会有一个默认值,并且属性赋值的顺序不受限制。有些书里称属性赋值的参数为“具名参数”。
自定义Attribute 实例
在此,我们不使用.NET Framework 中的各种Attribute 系统特性,而是从头自定义一个全新的Attribute 类。
示例代码如下:
using System;
namespace Con_Attribute
{
classProgram3
{
staticvoidMain(string[] args)
{
//使用反射读取Attribute
System.Reflection.MemberInfo info =typeof(Student);//通过反射得到Student类的信息
Hobby hobbyAttr =(Hobby)Attribute.GetCustomAttribute(info,typeof(Hobby));
if(hobbyAttr !=null)
{
Console.WriteLine("类名:{0}", info.Name);
Console.WriteLine("兴趣类型:{0}", hobbyAttr.Type);
Console.WriteLine("兴趣指数:{0}", hobbyAttr.Level);
}
}
}
//注意:"Sports" 是给构造函数的赋值, Level = 5 是给属性的赋值。
[Hobby("Sports",Level=5)]
classStudent
{
[Hobby("Football")]
publicstring profession;
publicstringProfession
{
get {return profession;}
set{ profession = value;}
}
}
//建议取名:HobbyAttribute
classHobby:Attribute// 必须以System.Attribute 类为基类,规范的写法一般是HobbyAttribute,用的时候可以简写为[Hobby(“”)]
{
// 参数值为null的string 危险,所以必需在构造函数中赋值
publicHobby(string _type)// 定位参数
{
this.type = _type;
}
//兴趣类型
privatestring type;
publicstringType
{
get {return type;}
set{ type = value;}
}
//兴趣指数
privateint level;
publicintLevel
{
get {return level;}
set{ level = value;}
}
}
}
classPerson:Attribute{
privatestring _name;
privateint _age;
publicstringName{
set{this._name = value;}
get {returnthis._name;}
}
publicintAge{
set{this._age = value;}
get {returnthis._age;}
}
publicPerson(string s,int i){
this.Name= s;
this.Age= i;
}
}
[Person("spike",23)]
class test {
privateint aa;
publicstring ss;
}
Person per;
foreach(var item intypeof(test).GetCustomAttributes(true)){
per = item asPerson;//若item是自定义的Person类,则将Person类返回
if(per !=null){
Console.WriteLine(per.Name);
Console.WriteLine(per.Age);
}
}
Console.ReadKey();