属性的使用
为了对属性进行测试,我们创建一个名字为MyMath的简单类,并给它添加二个函数,然后给它指定bugfix属性。
[BugFixAttribute(121,"JesseLiberty","01/03/05")]
[BugFixAttribute(107,"JesseLiberty","01/04/05",
Comment="Fixedoffbyoneerrors")]
publicclassMyMath
这些数据将与元数据存储在一起。下面是完整的源代码及其输出:
自定义属性
usingSystem;
//创建被指派给类成员的自定义属性
[AttributeUsage(AttributeTargets.Class,
AllowMultiple=true)]
publicclassBugFixAttribute:System.Attribute
{
//位置参数的自定义属性构造器
publicBugFixAttribute
(intbugID,
stringprogrammer,
stringdate)
{
this.bugID=bugID;
this.programmer=programmer;
this.date=date;
}
publicintBugID
{
get
{
returnbugID;
}
}
//命名参数的属性
publicstringComment
{
get
{
returncomment;
}
set
{
comment=value;
}
}
publicstringDate
{
get
{
returndate;
}
}
publicstringProgrammer
{
get
{
returnprogrammer;
}
}
//专有成员数据
privateintbugID;
privatestringcomment;
privatestringdate;
privatestringprogrammer;
}
//把属性指派给类
[BugFixAttribute(121,"JesseLiberty","01/03/05")]
[BugFixAttribute(107,"JesseLiberty","01/04/05",
Comment="Fixedoffbyoneerrors")]
publicclassMyMath
{
publicdoubleDoFunc1(doubleparam1)
{
returnparam1+DoFunc2(param1);
}
publicdoubleDoFunc2(doubleparam1)
{
returnparam1/3;
}
}
publicclassTester
{
publicstaticvoidMain()
{
MyMathmm=newMyMath();
Console.WriteLine("CallingDoFunc(7).Result:{0}",
mm.DoFunc1(7));
}
}
输出:
CallingDoFunc(7).Result:9.3333333333333339
象我们看到的那样,属性对输出绝对没有影响,创建属性也不会影响代码的性能。到目前为止,读者也只是在听我论述有关属性的问题,使用ILDASM浏览元数据,就会发现属性确实是存在的。