2015-04-24 48 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; 
}