C# Attribute

來源:互聯網
上載者:User

特性,就是為目標元素,可以是資料集、模組、類、屬性、方法、甚至函數參數等加入附加資訊,類似於注釋,但是可以在運行期以反射的方式獲得。定製特性主要應用在序列化、編譯器指令、設計模式等方面。

 

多個特性可以應用於同一元素,特性間以逗號隔開,以下表達規則有效:[AttributeUsage][ Flags]、[AttributeUsage, Flags]、[Flags, AttibuteUsageAttribute]、[AttributeUsage(), FlagesAttribute()]

attibute執行個體,是在編譯期進行初始化,而不是運行期。

C#允許以指定的首碼來表示特性所應用的目標元素,建議這樣來處理,因為顯式處理可以消除可能帶來的二義性。例如:

namespace Anytao.net 
{
    [assembly: MyAttribute(1)]          //應用於程式集
    [moduel: MyAttribute(2)]            //應用於模組
    pubic class Attribute_how2do
    {
        //
    } 
}

 

AttributeUsageAttribute特性的作用:Specifies the usage of another attribute class.

往往在定義新特性時應用以前的特性。

[AttributeUsageAttribute(AttributeTarget.All),
AllowMultiple = true, 
Inherited = true]
class MyNewAttribute: System.Attribute
{
   //

 

  1. 特性不會影響應用元素的任何功能,只是約定了該元素具有的特質。
  2. 所有非抽象特性必須具有public訪問限制。
  3. 特性常用於編譯器指令,突破#define, #undefine, #if, #endif的限制,而且更加靈活。
  4. 特性常用於在運行期獲得代碼注釋資訊,以附加資訊來最佳化調試。
  5. 特性可以應用在某些設計模式中,如原廠模式。
  6. 特性還常用於位標記,非託管函數標記、方法廢棄標記等其他方面。

下面是很詳細的Attribute應用教程:

Attribute在.net編程中的應用(一)
Attribute在.net編程中的應用(二)
Attribute在.NET編程中的應用(三)
Attribute在.NET編程中的應用(四)
Attribute在.NET編程中的應用(五)
Attribute在.NET編程中的應用(六)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.