C#反射訪問屬性規(guī)范及示例
如果沒有檢索自定義屬性的信息和對其進(jìn)行操作的方法,則定義自定義屬性并將其放置在源代碼中就沒有意義。C# 具有一個反射系統(tǒng),可用來檢索用自定義屬性定義的信息。主要方法是 GetCustomAttributes,它返回對象數(shù)組,這些對象在運行時等效于源代碼屬性。此方法具有多個重載版本。有關(guān)更多信息,請參見 Attribute。
C#反射——屬性規(guī)范
C#
- [Author("H. Ackerman", version = 1.1)]
- class SampleClass
在概念上等效于:
C#
- Author anonymousAuthorObject = new Author("H. Ackerman");
- anonymousAuthorObject.version = 1.1;
但是,直到查詢 SampleClass 以獲取屬性時才會執(zhí)行此代碼。對 SampleClass 調(diào)用 GetCustomAttributes 會導(dǎo)致按上述方式構(gòu)造并初始化一個 Author 對象。如果類還有其他屬性,則其他屬性對象的以類似方式構(gòu)造。然后 GetCustomAttributes 返回 Author 對象和數(shù)組中的任何其他屬性對象。之后就可以對此數(shù)組進(jìn)行迭代,確定根據(jù)每個數(shù)組元素的類型所應(yīng)用的屬性,并從屬性對象中提取信息。
C#反射——示例
下面是一個完整的示例。定義一個自定義屬性,將其應(yīng)用于若干實體并通過反射進(jìn)行檢索。
C#
- [System.AttributeUsage(System.AttributeTargets.Class |
- System.AttributeTargets.Struct,
- AllowMultiple = true) // multiuse attribute
- ]
- public class Author : System.Attribute
- {
- string name;
- public double version;
- public Author(string name)
- {
- this.name = name;
- version = 1.0; // Default value
- }
- public string GetName()
- {
- return name;
- }
- }
- [Author("H. Ackerman")]
- private class FirstClass
- {
- // ...
- }
- // No Author attribute
- private class SecondClass
- {
- // ...
- }
- [Author("H. Ackerman"), Author("M. Knott", version = 2.0)]
- private class ThirdClass
- {
- // ...
- }
- class TestAuthorAttribute
- {
- static void Main()
- {
- PrintAuthorInfo(typeof(FirstClass));
- PrintAuthorInfo(typeof(SecondClass));
- PrintAuthorInfo(typeof(ThirdClass));
- }
- private static void PrintAuthorInfo(System.Type t)
- {
- System.Console.WriteLine("Author information for {0}", t);
- System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // reflection
- foreach (System.Attribute attr in attrs)
- {
- if (attr is Author)
- {
- Author a = (Author)attr;
- System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version);
- }
- }
- }
- }
輸出
Author information for FirstClass
H. Ackerman, version 1.00
Author information for SecondClass
Author information for ThirdClass
H. Ackerman, version 1.00
M. Knott, version 2.00
本文關(guān)于C#反射訪問屬性的問題就介紹到這里。
【編輯推薦】