2015-04-24 49 views
2

新手PostSharp時失蹤。考慮以下代碼:自定義屬性使用基於PostSharp屬性

using System; 
using PostSharp.Aspects; 

namespace PostSharp1 { 

    [AttributeUsage(AttributeTargets.Property)][Serializable]public class Field1Attribute : System.Attribute { } 
    [AttributeUsage(AttributeTargets.Property)][Serializable]public class Field2Attribute : LocationInterceptionAspect { } 

    public class Person { 
     [Field1][Field2]public string Name { get; set; } 
    } 

    class Program { 

     static void Main(string[] args) { 

      var Friend = new Person(); 
      Friend.Name = "Fred Bloggs"; 

      var Properties = Friend.GetType().GetProperties(); 
      Console.WriteLine("Properties: " + Properties.Length); 
      var Count1 = 1; 
      foreach (var Property in Properties) { 
       var CustomAttributes = Property.GetCustomAttributes(false); 
       Console.WriteLine(" Property #" + Count1++ + ": " + Property.Name + ", # custom attributes = " + CustomAttributes.Length); 
       var Count2 = 1; 
       foreach (System.Attribute CustomAttribute in CustomAttributes) { 
        Console.WriteLine(" Attribute #" + Count2++ + ": " + CustomAttribute.ToString()); 
       } 
      } 
     } 

    } 

} 

一個使用反射來列出小Person類的屬性上的自定義屬性的組裝示例。

程序將列出Field1Attribute(基於System.Attribute),但Field2Attribute似乎已被剝離出來,因爲它是沒有上市。

只是想了解這裏的機制,爲什麼LocationInterceptionAspect衍生屬性丟失。

回答

2

真奇怪,有時只是寫了這個問題讓您研究的答案。這是「按設計」 - 方面(派生自System.Attribute)在應用後會被刪除。由於PostSharp完全是關於構建時間的,所以這很有意義。但是,可以按照文檔中的說明防止它們被移除:

1.1.5。反映看點實例在運行時

屬性播已初步設計作爲一種機制方面添加到程序。大多數情況下,表示某個方面的自定義屬性可以在應用該方面後移除。默認情況下,如果你 添加一個方面的程序並使用 反彙編器或系統中所產生的程序看。反思,你不會找到這些對應的自定義屬性。

如果您需要方面(或任何其他 組播屬性)通過的System.Reflection或任何其他 工具中反映出來,您必須將 MulticastAttributeUsageAttributePersistMetaData屬性設置爲true。對於 實例:

[MulticastAttributeUsage(MulticastTargets.Class, PersistMetaData = true)] 
public class TagAttribute : MulticastAttribute 
{ 
public string Tag; 
}