【问题标题】:Custom attribute missing when using PostSharp based attributes使用基于 PostSharp 的属性时缺少自定义属性
【发布时间】:2015-04-24 22:04:51
【问题描述】:

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 派生属性。

【问题讨论】:

    标签: custom-attributes postsharp


    【解决方案1】:

    奇怪的是,有时仅仅写出问题就可以让您研究答案。这是“设计使然” - 方面(派生自 System.Attribute)在应用后会被删除。有点道理,因为 PostSharp 真的是关于构建时间。但是,可以按照文档中的说明阻止它们被删除:

    1.1.5。在运行时反映方面实例

    属性多播主要被设计为一种向程序添加方面的机制。大多数情况下,表示方面的自定义属性可以在应用方面后删除。默认情况下,如果您 向程序添加一个方面并使用 反汇编程序或系统。反思,你不会发现这些 对应的自定义属性。

    如果你需要你的方面(或任何其他 多播属性)由 System.Reflection 或任何其他反射 工具,您必须设置 MulticastAttributeUsageAttributePersistMetaData 属性为 true。为了 实例:

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

    【讨论】:

      猜你喜欢
      • 2016-03-19
      • 2010-12-05
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 2019-12-11
      • 1970-01-01
      相关资源
      最近更新 更多