Attribute首先是一個類,在C#中, Attribute是作為編譯器指令來處理的
在.NET中,屬性的作用非常重要,無論是寫WEB控制項或是WEB服務,屬性的作用幾乎不可或缺,而序列化.程式安裝特徵等更離不開屬性,看上去很神秘,其實寫一個屬於自己的屬性也不難,在CodeProject和C#Corner上都有類似的示範代碼.這下面只是普通屬性,如果是AOP,則需要從ContextAttribute中繼承,關於AOP以及ContextAttribute,以後的文章將會專門講述,Code Project上也有相關的例子
using System;
namespace Test
{
// Only allow this attribute to be added to classes
[AttributeUsage(AttributeTargets.Class)]
public class TestAttribute : Attribute
{
// A number with some imaginary importance
public int TheNumber;
// A string that could be useful somewhere
public string Name;
// The only constructor requiring that
// TheNumber be set
public TestAttribute(int TheNumber)
{
this.TheNumber = TheNumber;
Name = "None";
}
// Method to illustrate that an attribute is really just
// a class at heart. This will be used in Driver.cs
public void PrintOut()
{
Console.WriteLine("/tTheNumber = {0}", TheNumber);
Console.WriteLine("/tName = /"{0}/"", Name);
}
}
}
上面就是一個屬性類了,很簡單的,注意的是,屬性類前面必須加上AttributeUsage屬性描述,裡面的AttributeTargets定義了該屬性的應用範圍,比如只應用於方法還是類還是全部適用,在上面這段代碼中,設定該屬性只能被類使用
你就可以在自己的類中用上自己的屬性了,比如
[Test(4, Name = "TestClassB")]
public class TestMyAtt
{}
仔細看,首先在TestAttribute 類的構造方法中,需要初始化TheNumber屬性,所以,在用TestAttribute的時候,必須有整數值,而Name 根據實際情況則可有可無了
實現自己的屬性其實還是很有用處的,個人認為對實現AOP模式是大有裨益的.