custom-attributes - 使用基于 PostSharp 的属性时缺少自定义属性

标签 custom-attributes 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());
                }
            }
        }

    }

}

一个虚构的示例,它使用 Reflection 列出小型 Person 类的属性上的自定义属性。

程序列出了 Field1Attribute(基于 System.Attribute),但 Field2Attribute 似乎已被删除,因为它未列出。

只是想了解这里的机制以及为什么缺少 LocationInterceptionAspect 派生属性。

最佳答案

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

1.1.5. Reflecting Aspect Instances at Runtime

Attribute multicasting has been primarily designed as a mechanism to add aspects to a program. Most of the time, the custom attribute representing an aspect can be removed after the aspect has been applied. By default, if you add an aspect to a program and look at the resulting program using a disassembler or System. Reflection, you will not find these corresponding custom attributes.

If you need your aspect (or any other multicast attribute) to be reflected by System.Reflection or any other tool, you have to set the MulticastAttributeUsageAttributePersistMetaData property to true. For instance:

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

关于custom-attributes - 使用基于 PostSharp 的属性时缺少自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29858305/

相关文章:

xsd - 将元数据添加到 XSD 定义

c# - 生成多个属性?

c# - 包括使用 PostSharp、Log4Net 和 Unity 的附加属性

postsharp - 获取参数名称

html - JSF 不呈现自定义 HTML 标记属性

c# - 我的 ViewModel 列表中每个项目的数据验证

c# - 在多个成员上使用 Postsharp 方面,无需对其进行多播

c# - 您如何反射(reflection)应用于返回值的属性?

c# - pdb 文件在 PostSharp 后丢失

c# - 为什么将 MemberInfo.GetCustomAttributes(Type) 定义为返回属性数组?