嗯,你問的不一定與面向方面編程有關。相反,AOP框架通常使用屬性來標記所謂的「切入點」,即。 「建議」被應用的地方(即類型將被修改的地方)。
通常,改變班級行爲不是屬性本身;他們只是通過別的東西「標記」某種類型的特殊治療,例如,由另一個框架,庫,字節碼重寫器等......或者簡單地由.NET本身。
有一些是.NET其「修改」一類,甚至沒有需要任何額外的工具—他們將通過.NET的執行環境區別對待的intrinsical部分特殊屬性。 MarshalByRefObjectAttribute
可能就是其中之一。 SerializableAttribute
是另一個對處理序列化的.NET BCL部分很重要的一個。
Windows窗體設計器爲Visual Studio俯瞰針對某些屬性,如Browsable
,Description
等
WCF俯瞰的屬性,如OperationContract
,DataContract
等
這裏要理解的要點是,有人(即使它本身就是.NET本身)必須主動檢查屬性的存在並做些事情;他們不會自己做任何事情!他們只是註釋了其他數據。
您可以編寫自己的組件來獲取對象,並查看對象的類型是否具有在其上定義的屬性(如果是,則以其他方式繼續)。這可以通過反射來完成:
using System.Linq;
using System.Reflection;
…
public class SomeAttribute : Attribute { … }
void DoSomethingWith<T>(T someObject) // (T is only introduced here for
{ // easy reference in the comments below.)
object[] attribute =
someObject.GetType().GetCustomAttributes(typeof(SomeAttribute), true);
if (attribute.Any())
{
// [SomeAttribute] is present on type T, or T inherits the attribute.
}
else
{
// [SomeAttribute] is not present on T.
}
}
又見對文檔的MSDN:System.Type.GetCustomAttributes