翻譯不是為了翻譯,是為了學(xué)習!因為只有翻譯我才能逐句的看完整篇文章。
當然還可以得到各位達人的斧正,讓我由懂得皮毛到漸入佳境!樂(lè )哉,幸哉!
約定:
1.”attribute”和”attributes”均不翻譯
2.”property”譯為“屬性”
3.msdn中的原句不翻譯
4.”program entity”譯為”語(yǔ)言元素”
Attributes in C#
介紹
Attributes是一種新的描述信息,我們既可以使用attributes來(lái)定義設計期信息(例如 幫助文件,文檔的URL),還可以用attributes定義運行時(shí)信息(例如,使XML中的元素與類(lèi)的成員字段關(guān)聯(lián)起來(lái))。我們也可以用attributes來(lái)創(chuàng )建一個(gè)“自描述”的組件。在這篇指南中我們將明白怎么創(chuàng )建屬性并將其綁定至各種語(yǔ)言元素上,另外我們怎樣在運行時(shí)環(huán)境下獲取到attributes的一些信息。
定義
MSDN 中做如下定義(ms-help://MS.MSDNQTR.2002APR.1033/csspec/html/vclrfcsharpspec_17_2.htm)
"An attribute is a piece of additional declarative information that is specified for a declaration."
使用預定義 Attributes
在c#中已有一小組預定義的attributes,在我們學(xué)習怎樣創(chuàng )建自定義attributes前,先來(lái)了解下在我們的代碼中使用那些預定義的attributes.
仔細看下該實(shí)例,在該實(shí)例中我們用到了”Obsolete”attribute,它標記了一個(gè)不該再被使用的語(yǔ)言元素(譯者注:這里的元素為方法),該屬性的第一個(gè)參數是string類(lèi)型,它解釋為什么該元素被荒棄,以及我們該使用什么元素來(lái)代替它。實(shí)際中,我們可以書(shū)寫(xiě)任何其它文本來(lái)代替這段文本。第二個(gè)參數是告訴編譯器把依然使用這被標識的元素視為一種錯誤,這就意味著(zhù)編譯器會(huì )因此而產(chǎn)生一個(gè)警告。
當我們試圖編譯上面的上面的程序,我們會(huì )得到如下錯誤:
AnyClass.Old()' is obsolete: 'Don't use Old method, use New method'
開(kāi)發(fā)自定義Attributes
現在我們即將了解怎么開(kāi)發(fā)自定義的attributes。這兒有個(gè)小小處方,有它我們就可以學(xué)會(huì )創(chuàng )建自定義的attributes。
在C#中,我們的attribute類(lèi)都派生于System.Attribute類(lèi) (Aclass that derives from the abstract class System.Attribute, whetherdirectly or indirectly, is an attribute class. The declaration of anattribute class defines a new kind of attribute that can be placed on adeclaration) ,我們就這么行動(dòng)吧。
不管你是否相信我,就這樣我們就已經(jīng)創(chuàng )建了一個(gè)自定義
attribute?,F在就可以用它來(lái)裝飾我們的類(lèi)了,就像我們使用obsolete attribute一樣。
注意:按慣例我們是用”Attribute“作為attribute類(lèi)名的后綴,然而,當我們當我們把attribute綁定到某語(yǔ)言元素時(shí),是不包含“Attribute“后綴的。編譯器首先在System.Attribute 的繼承類(lèi)中查找該attribute,如果沒(méi)有找到,編譯器會(huì )把“Attribute“追加到該attribute的名字后面,然后查找它。
但是迄今為止,該attribute沒(méi)有任何用處。為了使它有點(diǎn)用處,讓我們在它里面加點(diǎn)東西吧。
在上面的例子中,我們在attribute類(lèi)中添加了一個(gè)屬性,在最后一節中,我們將在運行時(shí)查詢(xún)該屬性。
定義或控制自定義Attribute的用法
AttributeUsage 類(lèi)是另一預定義類(lèi)(譯者注:attribute類(lèi)本身用這個(gè)atrribute System.AttributeUsage來(lái)標記),它將幫助我們控制我們自定義attribute的用法,這就是,我們能為自定義的attribute類(lèi)定義attributes。
它描述了一個(gè)自定義attribute類(lèi)能被怎樣使用。
AttributeUsage 提供三個(gè)屬性,我們能將它們放置到我們的自定義attribute類(lèi)上, 第一個(gè)特性是:
ValidOn
通過(guò)這個(gè)屬性,我們能指定我們的自定義attribute可以放置在哪些語(yǔ)言元素之上。這組我們能把自定義attribute類(lèi)放置其上的語(yǔ)言元素被放在枚舉器AttributeTargets 中。我們可以使用bitwise(譯者注:這個(gè)詞不知道怎么翻譯好,但他的意思是可以這么用:[AttributeUsage((AttributeTargets)4, AllowMultiple = false, Inherited = false )],4代表就是“class”元素,其它諸如1代表“assembly”,16383代表“all”等等)或者”.”操做符綁定幾個(gè)AttributeTargets 值。(譯者注:默認值為AttributeTargets.All)
AllowMultiple
該屬性標識我們的自定義attribte能在同一語(yǔ)言元素上使用多次。(譯者注:該屬性為bool類(lèi)型,默認值為false,意思就是該自定義attribute在同一語(yǔ)言元素上只能使用一次)
Inherited
我們可以使用該屬性來(lái)控制我們的自定義attribute類(lèi)的繼承規則。該屬性標識我們的自定義attribute是否可以由派生類(lèi)繼承。((譯者注:該屬性為bool類(lèi)型,默認值為false,意思是不能繼承)
讓我們來(lái)做點(diǎn)實(shí)際的東西吧,我們將把AttributeUsage attribute 放置在我們的help attribute 上并在它的幫助下,我們來(lái)控制help attribute的用法。
首先我們注意 AttributeTargets.Class. 它規定這個(gè)help attribute 只能放置在語(yǔ)言元素”class”之上。這就意味著(zhù),下面的代碼將會(huì )產(chǎn)生一個(gè)錯誤。
AnyClass.cs: Attribute 'Help' is not valid on this declaration type.
It is valid on 'class' declarations only.
現在試著(zhù)把它綁定到方法。
我們可以使用 AttributeTargets.All 來(lái)允許 Help attribute 可以放置在任何預定義的語(yǔ)言元素上,那些可能的語(yǔ)言元素如下:
它產(chǎn)生了一個(gè)編譯錯誤:
[Help("it contains a do-nothing method")]
public class AnyClass
{
[Help("this is a do-nothing method")] //error
public void AnyMethod()
{
}
}
AnyClass.cs: Duplicate 'Help' attribute
Ok!現在我們該討論下最后那個(gè)屬性了,”Inherited”, 指出當把該attribute放置于一個(gè)基類(lèi)之上,是否派生類(lèi)也繼承了該attribute。如果綁定至某個(gè)attribute類(lèi)的”Inherited”被設為true,那么該attribute就會(huì )被繼承,然而如果綁定至某個(gè)attribute類(lèi)的”Inherited”被設為false或者沒(méi)有定義,那么該attribute就不會(huì )被繼承。
讓我們假設有如下的類(lèi)關(guān)系。
我們有四種可能的綁定
:第一種情況
如果我們查詢(xún)(我們將在后面來(lái)了解如何在運行時(shí)來(lái)查詢(xún)attributes)派生類(lèi)中的help attribute,我們將不可能查詢(xún)到因為”Inherited”被設為了false。
第二種情況
第二種情況沒(méi)有什么不同,因為其”Inherited”也被設為了false。
第三種情況
為了解釋第三種和第四種情況,讓我們?yōu)榕缮?lèi)也綁定同一attribute。
現在我們查詢(xún)相關(guān)的
help attribute ,我們將僅僅可以得到派生類(lèi)的attribute,為什么這樣是因為help attribute雖然允許被繼承,但不能多次在同一語(yǔ)言元素上使用,所以基類(lèi)中的help attribute被派生類(lèi)的help attribute 重寫(xiě)了。第四種情況
在第四種情況中,當我們查詢(xún)派生類(lèi)的help attribute 時(shí),我們可以得到兩個(gè)attributes,當然是因為help attribute既允許被繼承,又允許在同一語(yǔ)言元素上多次使用的結果。
注意:AttributeUsage attribute 僅應用在那種是System.Attribute 派生的attriubte類(lèi)而且綁定值該attriubte類(lèi)的AllowMultiple和Inherited均為false上才是有效的。
可選參數 vs. 命名參數
可選參數是attribute類(lèi)構造函數的參數。它們是強制的,必須在每次在attribute綁定至某語(yǔ)言元素時(shí)提供一個(gè)值。而另一方面,命名參數倒是真正的可選參數,不是在attribute構造函數的參數。
為了更加詳細的解釋?zhuān)屛覀冊?/span>Help類(lèi)中添加另外的屬性。
當我們在
Inherited = false)]
public class HelpAttribute : Attribute
{
public HelpAttribute(String Description_in)
{
this.description = Description_in;
this.verion = "No Version is defined for this class";
}
protected String description;
public String Description
{
get
{
return this.description;
}
}
protected String version;
public String Version
{
get
{
return this.version;
}
//if we ever want our attribute user to set this property,
//we must specify set method for it
set
{
this.verion = value;
}
}
}
[Help("This is Class1")]
public class Class1
{
}
[Help("This is Class2", Version = "1.0")]
public class Class2
{
}
[Help("This is Class3", Version = "2.0",
Description = "This is do-nothing class")]
public class Class3
{
}
Help.Description : This is Class1
Help.Version :No Version is defined for this class
因為我們沒(méi)有為Version這個(gè)屬性定義任何任何值,所以在構造函數中設定的值被我們查詢(xún)出來(lái)了。如果沒(méi)有定義任何值,那么就會(huì )賦一個(gè)該類(lèi)型的默認值(例如:如果是int型,默認值就是0)。
現在,查詢(xún)Class2的結果是:
Help.Description : This is Class2
Help.Version : 1.0
我們不能為了可選參數而使用多個(gè)構造函數,應該用已命名參數來(lái)代替。我們之所以稱(chēng)它們?yōu)橐衙?,是因為當我們在構造函數為它們提供值時(shí),我們必須命名它們。例如,在第二個(gè)類(lèi)中,我們如是定義Help。
[Help("This is Class2", Version = "1.0")]
在 AttributeUsage 例子中, 參數”ValidOn”是可選參數,而“Inherited“和“AllowMultiple“ 是命名參數。
注意:為了在attribute的構造函數中設定命名參數的值,我們必須為相應的屬性提供一個(gè)set方法否則會(huì )引起編譯期錯誤:
'Version' : Named attribute argument can't be a read only property
現在,我們在Class3中查找Help attribute 及其屬性會(huì )發(fā)生什么呢?結果是跟上面提到的相同的編譯期錯誤。
'Desciption' : Named attribute argument can't be a read only property
現在我們修改下Help類(lèi),為屬性”Description”加一個(gè)set方法?,F在的輸出就是:
Help.Description : This is do-nothing class
Help.Version : 2.0
在屏幕后面究竟發(fā)生了什么呢?首先帶有可選參數的構造函數被調用,然后,每個(gè)命名參數的set方法被調用,在構造函數中賦給命名參數的值被set方法所覆寫(xiě)。
參數類(lèi)型
一個(gè)attribute類(lèi)的參數類(lèi)型被限定在如下類(lèi)型中:
Attributes 標記
假設,我們想把Help attribute 綁定至元素 assembly。第一個(gè)問(wèn)題是我們要把Help attribute 放在哪兒才能讓編譯器確定該attribute是綁定至整個(gè)assembly呢?考慮另一種情況,我們想把attribute綁定至一個(gè)方法的返回類(lèi)型上,怎樣才能讓編譯器確定我們是把attribute綁定至方法的返回類(lèi)型上,而不是整個(gè)方法呢?
為了解決諸如此類(lèi)的含糊問(wèn)題,我們使用attribute標識符,有了它的幫助,我們就可以確切地申明我們把attribute 綁定至哪一個(gè)語(yǔ)言元素。
例如:
[assembly: Help("this a do-nothing assembly")]
這個(gè)在Help attribute 前的assembly標識符確切地告訴編譯器,該attribute被綁定至整個(gè)assembly??赡艿臉俗R符有:
在運行時(shí)查詢(xún)Attributes
現在我們明白怎么創(chuàng )建attribtes和把它們綁定至語(yǔ)言元素。是時(shí)候來(lái)學(xué)習類(lèi)的使用者該如何在運行時(shí)查詢(xún)這信息。
為了查詢(xún)一語(yǔ)言元素上綁定的attributes,我們必須使用反射。反射有能力在運行時(shí)發(fā)現類(lèi)型信息。
我們可以使用.NET Framework Reflection APIs 通過(guò)對整個(gè)assembly元數據的迭代,列舉出assembly中所有已定義的類(lèi),類(lèi)型,還有方法。
記住那舊的Help attribute 和AnyClass 類(lèi)。
我們將在接下來(lái)的兩節中在我們的
using System.Reflection;
using System.Diagnostics;
//attaching Help attribute to entire assembly
[assembly : Help("This Assembly demonstrates custom attributes
creation and their run-time query.")]
//our custom attribute class
public class HelpAttribute : Attribute
{
public HelpAttribute(String Description_in)
{
//
// TODO: Add constructor logic here
this.description = Description_in;
//
}
protected String description;
public String Description
{
get
{
return this.deescription;
}
}
}
//attaching Help attribute to our AnyClass
[HelpString("This is a do-nothing Class.")]
public class AnyClass
{
//attaching Help attribute to our AnyMethod
[Help("This is a do-nothing Method.")]
public void AnyMethod()
{
}
//attaching Help attribute to our AnyInt Field
[Help("This is any Integer.")]
public int AnyInt;
}
class QueryApp
{
public static void Main()
{
}
}
查詢(xún)程序集的Attributes
在接下來(lái)的代碼中,我們先得到當前的進(jìn)程名稱(chēng),然后用Assembly類(lèi)中的LoadForm()方法加載程序集,再有用GetCustomAttributes()方法得到被綁定至當前程序集的自定義attributes,接下來(lái)用foreach語(yǔ)句遍歷所有attributes并試圖把每個(gè)attribute轉型為Help attribute(即將轉型的對象使用as關(guān)鍵字有一個(gè)優(yōu)點(diǎn),就是當轉型不合法時(shí),我們將不需擔心會(huì )拋出異常,代之以空值(null)作為結果),接下來(lái)的一行就是檢查轉型是否有效,及是不是為空,跟著(zhù)就顯示Help attribute的“Description”屬性。
程序輸出如下:
{
public static void Main()
{
HelpAttribute HelpAttr;
//Querying Assembly Attributes
String assemblyName;
Process p = Process.GetCurrentProcess();
assemblyName = p.ProcessName + ".exe";
Assembly a = Assembly.LoadFrom(assemblyName);
foreach (Attribute attr in a.GetCustomAttributes(true))
{
HelpAttr = attr as HelpAttribute;
if (null != HelpAttr)
{
Console.WriteLine("Description of {0}:\n{1}",
assemblyName,HelpAttr.Description);
}
}
}
}
Description of QueryAttribute.exe:
This Assembly demonstrates custom attributes creation and
their run-time query.
Press any key to continue
查詢(xún)類(lèi)、方法、類(lèi)成員的Attributes
下面的代碼中,我們惟一不熟悉的就是Main()方法中的第一行。
Type type = typeof(AnyClass);
它用typeof操作符得到了一個(gè)與我們AnyClass類(lèi)相關(guān)聯(lián)的Type型對象。剩下的查詢(xún)類(lèi)attributes代碼就與上面的例子是相似的,應該不要解釋了吧(我是這么想的)。
為查詢(xún)方法和類(lèi)成員的attributes,首先我們得到所有在類(lèi)中存在的方法和成員,然后我們查詢(xún)與它們相關(guān)的所有attributes,這就跟我們查詢(xún)類(lèi)attributes一樣的方式。
The output of the following program is.
{
public static void Main()
{
Type type = typeof(AnyClass);
HelpAttribute HelpAttr;
//Querying Class Attributes
foreach (Attribute attr in type.GetCustomAttributes(true))
{
HelpAttr = attr as HelpAttribute;
if (null != HelpAttr)
{
Console.WriteLine("Description of AnyClass:\n{0}",
HelpAttr.Description);
}
}
//Querying Class-Method Attributes
foreach(MethodInfo method in type.GetMethods())
{
foreach (Attribute attr in method.GetCustomAttributes(true))
{
HelpAttr = attr as HelpAttribute;
if (null != HelpAttr)
{
Console.WriteLine("Description of {0}:\n{1}",
method.Name,
HelpAttr.Description);
}
}
}
//Querying Class-Field (only public) Attributes
foreach(FieldInfo field in type.GetFields())
{
foreach (Attribute attr in field.GetCustomAttributes(true))
{
HelpAttr= attr as HelpAttribute;
if (null != HelpAttr)
{
Console.WriteLine("Description of {0}:\n{1}",
field.Name,HelpAttr.Description);
}
}
}
}
}
Description of AnyClass:
This is a do-nothing Class.
Description of AnyMethod:
This is a do-nothing Method.
Description of AnyInt:
This is any Integer.
Press any key to continue
聯(lián)系客服