關于C# 中的Attribute 特性

作者: 鋼鋼  來源: 博客園  發布時間: 2011-01-09 23:30  閱讀: 41641 次  推薦: 32   原文鏈接   [收藏]  
摘要:糾結地說,這應該算是一篇關于Attribute 的筆記,其中的一些思路和代碼借鑒了他人的文筆(見本文底部鏈接)。但是,由于此文對Attribute 的講解實在是叫好(自夸一下 ^_^),所以公之于眾,希望能對大家有所幫助。

  Attribute與Property 的翻譯區別

  Attribute 一般譯作“特性”,Property 仍然譯為“屬性”。

  Attribute 是什么

  Attribute 是一種可由用戶自由定義的修飾符(Modifier),可以用來修飾各種需要被修飾的目標。

  簡單的說,Attribute就是一種“附著物” —— 就像牡蠣吸附在船底或礁石上一樣。

  這些附著物的作用是為它們的附著體追加上一些額外的信息(這些信息就保存在附著物的體內)—— 比如“這個類是我寫的”或者“這個函數以前出過問題”等等。

  Attribute 的作用

  特性Attribute 的作用是添加元數據。
  元數據可以被工具支持,比如:編譯器用元數據來輔助編譯,調試器用元數據來調試程序。

  Attribute 與注釋的區別

  • 注釋是對程序源代碼的一種說明,主要目的是給人看的,在程序被編譯的時候會被編譯器所丟棄,因此,它絲毫不會影響到程序的執行。
  • 而Attribute是程序代碼的一部分,不但不會被編譯器丟棄,而且還會被編譯器編譯進程序集(Assembly)的元數據(Metadata)里,在程序運行的時候,你隨時可以從元數據里提取出這些附加信息來決策程序的運行。

  舉例:

  在項目中,有一個類由兩個程序員(小張和小李)共同維護。這個類起一個“工具包”(Utilities)的作用(就像.NET Framework中的Math類一樣),里面含了幾十個靜態方法。而這些靜態方法,一半是小張寫的、一半是小李寫的;在項目的測試中,有一些靜態方法曾經出過bug,后來又被修正。這樣,我們就可以把這些方面劃分成這樣幾類:

Box

  我們分類的目的主要是在測試的時候可以按不同的類別進行測試、獲取不同的效果。比如:統計兩個人的工作量或者對曾經出過bug的方法進行回歸測試。

  如果不使用Attribute,為了區分這四類靜態方法,我們只能通過注釋來說明,但這種方式會有很多弊端;

  如果使用Attribute,區分這四類靜態方法將會變得簡單多了。示例代碼如下:

 
#define Buged
//C# 的宏定義必須出現在所有代碼之前。當前只讓 Buged 宏有效。
using System;
using System.Diagnostics; // 注意:這是為了使用包含在此名稱空間中的ConditionalAttribute特性
namespace Con_Attribute
{

class Program
{

static void Main(string[] args)
{

// 雖然方法都被調用了,但只有符合條件的才會被執行!
ToolKit.FunA();
ToolKit.FunB();
ToolKit.FunC();
ToolKit.FunD();
}
}

class ToolKit
{
[ConditionalAttribute(
"Li")] // Attribute名稱的長記法
[ConditionalAttribute("Buged")]
public static void FunA()
{
Console.WriteLine(
"Created By Li, Buged.");
}
[Conditional(
"Li")] // Attribute名稱的短記法
[Conditional("NoBug")]
public static void FunB()
{
Console.WriteLine(
"Created By Li, NoBug.");
}
[ConditionalAttribute(
"Zhang")]// Attribute名稱的長記法
[ConditionalAttribute("Buged")]
public static void FunC()
{
Console.WriteLine(
"Created By Zhang, Buged.");
}
[Conditional(
"Zhang")] // Attribute名稱的短記法
[Conditional("NoBug")]
public static void FunD()
{
Console.WriteLine(
"Created By Zhang, NoBug.");
}
}
}

  運行結果如下:

2010-12-21_113636

  注意:運行結果是由代碼中“#define Buged ”這個宏定義所決定。

  分析:

  1.  在本例中,我們使用了ConditionalAttribute 這個Attribute,它被包含在 System.Diagnostics 名稱空間中。顯然,它多半時間是用來做程序調試與診斷的。

  2.  與ConditionalAttribute 相關的是一組C# 宏,它們看起來與C語言的宏別無二致,位置必須出現在所有C# 代碼之前。顧名思義,ConditionalAttribute 是用來判斷條件的,凡被ConditionalAttribute (或Conditional)“附著”了的方法,只有滿足了條件才會執行。

  3.  Attribute 就像船底上可以附著很多牡蠣一樣,一個方法上也可以附著多個ConditionalAttribute 的實例。把Attribute 附著在目標上的書寫格式很簡單,使用方括號把Attribute 括起來,然后緊接著寫Attribute 的附著體就行了。當多個Attribute 附著在同一個目標上時,就把這些Attribute 的方括號一個挨一個地書寫(或者在一對方括號中書寫多個Attribute),而且不必在乎它們的順序。

  4.  在使用Attribute 的時候,有“長記法”和“短記法”兩種,請君自便。

  由上面的第3 條和第4 條我們可以推出,以下四種Attribute 的使用方式是完全等價:

 
// 長記法
[ConditionalAttribute("LI")]
[ConditionalAttribute(
"NoBug")]
public static void Fun()
{ Console.WriteLine(
"Created By Li, NoBug."); }
// 短記法
[Conditional("LI")]
[Conditional(
"NoBug")]
public static void Fun()
{ Console.WriteLine(
"Created By Li, NoBug."); }
// 換序
[Conditional("NoBug")]
[Conditional(
"LI")]
public static void Fun()
{ Console.WriteLine(
"Created By Li, NoBug."); }
// 單括號疊加
[Conditional("NoBug"), Conditional("LI")]
public static void Fun()
{ Console.WriteLine(
"Created By Li, NoBug."); }

  Attribute 的本質

  從上面的代碼中,我們可以看到Attribute 似乎總跟public、static 這些關鍵字(Keyword)出現在一起。

  莫非使用了Attribute 就相當于定義了新的修飾符(Modifier)嗎?讓我們來一窺究竟!

  示例代碼如下:

 
#define XG //C# 的宏定義必須出現在所有代碼之前
using System;
using System.Diagnostics; // 注意:這是為了使用包含在此名稱空間中的ConditionalAttribute 特性
namespace Con_Attribute
{

class Program2
{
[Conditional(
"XG")]
static void Fun()
{
Console.ForegroundColor
= ConsoleColor.Yellow;
Console.WriteLine(
"http://xugang.cnblogs.com");
}

static void Main(string[] args)
{
Fun();
}
}
}

  使用微軟的中間語言反編譯器查看 MSIL 中間語言中TargetMethod:void() 方法的代碼,截圖如下:

2010-12-21_122656

  可以看出:Attribute 本質上就是一個類,它在所附著的目標對象上最終實例化。

  仔細觀察中間語言(MSIL)的代碼之后,那些被C# 語言所掩蓋的事實,在中間語言(MSIL)中就變得赤身裸體了。而Attribute 也變得毫無秘密!

  圖中紅色所指的是Fun 方法及其修飾符,但Attribute 并沒有出現在這里。

  圖中藍色所指的是在調用mscorlib.dll 程序集中System.Diagnostics 名稱空間中ConditionalAttribute 類的構造函數。

  可見,Attribute 并不是修飾符,而是一個有著獨特實例化形式的類!

  Attribute 實例化有什么獨特之處呢?

  1.  它的實例是使用.custom 聲明的。查看中間語言語法,你會發現.custom 是專門用來聲明自定義特性的。

  2.  聲明Attribute 的位置是在函數體內的真正代碼(IL_0000  至IL_0014 )之前。

  這就從“底層”證明了Attribute不是什么“修飾符”,而是一種實例化方式比較特殊的類。

  元數據的作用

  MSIL 中間語言中,程序集的元數據(Metadata)記錄了這個程序集里有多少個namespace、多少個類、類里有什么成員、成員的訪問級別是什么。而且,元數據是以文本(也就是Unicode 字符)形式存在的,使用.NET的反射(Reflection)技術就能把它們讀取出來,并形成MSIL 中的樹狀圖、VS 里的Object  Browser 視圖,以及自動代碼提示功能,這些都是元數據與反射技術結合的產物。一個程序集(.EXE或.DLL)能夠使用包含在自己體內的元數據來完整地說明自己,而不必像C/C++ 那樣帶著一大捆頭文件,這就叫作“自包含性”或“自描述性”。

  Attribute 的實例化

  就像牡蠣天生就要吸附在礁石或船底上一樣,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
{

class Program3
{

static void Main(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)]
class Student
{
[Hobby(
"Football")]
public string profession;
public string Profession
{

get { return profession; }
set { profession = value; }
}
}

//建議取名:HobbyAttribute
class Hobby : Attribute // 必須以System.Attribute 類為基類
{
// 參數值為null的string 危險,所以必需在構造函數中賦值
public Hobby(string _type) // 定位參數
{
this.type = _type;
}

//興趣類型
private string type;
public string Type
{

get { return type; }
set { type = value; }
}

//興趣指數
private int level;
public int Level
{

get { return level; }
set { level = value; }
}
}
}

  為了不讓代碼太長,上面的示例中Hobby 類的構造函數只有一個參數,所以對“定位參數”體現的還不夠淋漓盡致。大家可以為Hobby 類再添加幾個屬性,并在構造函數里多設置幾個參數,體驗一下Attribute 實例化時對參數個數及參數位置的敏感性。

  能被Attribute 所附著的目標

  Attribute 可以將自己的實例附著在什么目標上呢?這個問題的答案隱藏在AttributeTargets 這個枚舉類型里。

  這個類型的可取值集合為:

All                                         Assembly                      Class                              Constructor

Delegate                           Enum                               Event                              Field

GenericParameter         Interface                         Method                           Module

Parameter                         Property                         ReturnValue                Struct

  一共是16 個可取值。上面這張表是按字母順序排列的,并不代表它們真實值的排列順序。

  使用下面這個小程序可以查看每個枚舉值對應的整數值,示例代碼如下:

 
using System;
namespace Con_Attribute
{

class Program4
{

static void Main(string[] args)
{
Console.WriteLine(
"Assembly\t\t\t{0}", Convert.ToInt32(AttributeTargets.Assembly));
Console.WriteLine(
"Module\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Module));
Console.WriteLine(
"Class\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Class));
Console.WriteLine(
"Struct\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Struct));
Console.WriteLine(
"Enum\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Enum));
Console.WriteLine(
"Constructor\t\t\t{0}", Convert.ToInt32(AttributeTargets.Constructor));
Console.WriteLine(
"Method\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Method));
Console.WriteLine(
"Property\t\t\t{0}", Convert.ToInt32(AttributeTargets.Property));
Console.WriteLine(
"Field\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Field));
Console.WriteLine(
"Event\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.Event));
Console.WriteLine(
"Interface\t\t\t{0}", Convert.ToInt32(AttributeTargets.Interface));
Console.WriteLine(
"Parameter\t\t\t{0}", Convert.ToInt32(AttributeTargets.Parameter));
Console.WriteLine(
"Delegate\t\t\t{0}", Convert.ToInt32(AttributeTargets.Delegate));
Console.WriteLine(
"ReturnValue\t\t\t{0}", Convert.ToInt32(AttributeTargets.ReturnValue));
Console.WriteLine(
"GenericParameter\t\t{0}", Convert.ToInt32(AttributeTargets.GenericParameter));
Console.WriteLine(
"All\t\t\t\t{0}", Convert.ToInt32(AttributeTargets.All));
Console.WriteLine(
"\n");
}
}
}

  結果顯示如下:

2010-12-21_232331

  AttributeTargets 使用了枚舉值的另一種用法 —— 標識位。
  除了All 的值之外,每個值的二進制形式中只有一位是“1”,其余位全是“0”。
  如果我們的Attribute 要求既能附著在類上,又能附著在類的方法上。就可以使用C# 中的操作符“|”(也就是按位求“或”)。有了它,我們只需要將代碼書寫如下:

  AttributeTargets.Class  |  AttributeTargets.Method

  因為這兩個枚舉值的標識位(也就是那個唯一的“1”)是錯開的,所以只需要按位求或就解決問題了。

  這樣,你就能理解:為什么AttributeTargets.All 的值是32767 了。

  默認情況下,當我們聲明并定義一個新的Attribute 類時,它的可附著目標是AttributeTargets.All。

  大多數情況下,AttributeTargets.All 就已經滿足需求了。不過,如果你非要對它有所限制,那就要費點兒周折了。

  例如,你想把前面的Hobby 類的附著目標限制為只有“類”和“字段”使用,則示例代碼如下:

 
[AttributeUsage(AttributeTargets.Class, AttributeTargets.Field)]
class Hobby : Attribute // 必須以System.Attribute 類為基類
{
// Hobby 類的具體實現
}

  這里是使用Attribute的實例(AttributeUsage)附著在Attribute 類(Hobby)上。Attribute 的本質就是類,而AttributeUsage 又說明Hobby 類可以附著在哪些類型上。

  附加問題:

  1.  如果一個Attribute 類附著在了某個類上,那么這個Attribute 類會不會隨著繼承關系也附著在派生類上呢?

  2.  可不可以像多個牡蠣附著在同一艘船上那樣,讓一個Attribute 類的多個實例附著在同一個目標上呢?

  答案:可以。代碼如下:

 
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
class Hobby : System.Attribute
{

// Hobby 類的具體實現
}

  AttributeUsage 這個專門用來修飾Attribute 的Attribute ,除了可以控制修飾目標外,還能決定被它修飾的Attribute 是否可以隨宿主“遺傳”,以及是否可以使用多個實例來修飾同一個目標!

  那修飾ConditionalAttribute 的AttributeUsage 又會是什么樣子呢?(答案在MSDN中)

  參考來源:

  Attribute 在.NET 編程的應用

  深入淺出Attribute[上] —— Attribute 初體驗

  深入淺出Attribute[中] —— Attribute本質論 

  示例代碼

32
0
 
標簽:C# Attribute
 
 

文章列表

全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣()