Custom attributes 使用基于PostSharp的属性时缺少自定义属性
新手到波斯夏普。考虑下面的代码:Custom attributes 使用基于PostSharp的属性时缺少自定义属性,custom-attributes,postsharp,Custom Attributes,Postsharp,新手到波斯夏普。考虑下面的代码: using System; using PostSharp.Aspects; namespace PostSharp1 { [AttributeUsage(AttributeTargets.Property)][Serializable]public class Field1Attribute : System.Attribute { } [AttributeUsage(AttributeTargets.Property)][Serializ
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());
}
}
}
}
}
一个虚构的示例,它使用反射来列出小人类属性上的自定义属性
程序列出Field1属性(基于System.Attribute),但Field2属性似乎已被删除,因为它未列出
只是想了解这里的机制以及LocationInterceptionSpect派生属性丢失的原因。奇怪的是,有时仅仅写下问题就可以研究答案。这是“按设计”-应用方面(从System.Attribute派生)后将删除这些方面。这有点道理,因为PostSharp实际上都是关于构建时间的。但是,可以按照文档中的说明防止它们被移除: 1.1.5。在运行时反射方面实例 属性多播主要被设计为一种向程序添加方面的机制。大多数情况下,表示方面的自定义属性可以在应用方面后删除。默认情况下,如果 向程序添加方面,并使用 反汇编程序或系统。反思,你不会发现这些 相应的自定义属性 如果您需要您的方面(或任何其他方面) 多播属性)将由System.Reflection或任何其他 工具,您必须设置 MulticastAttributeUsageAttributePersistMetaData属性为true。对于 实例:
[MulticastAttributeUsage( MulticastTargets.Class, PersistMetaData = true )]
public class TagAttribute : MulticastAttribute
{
public string Tag;
}