PostSharp如何知道在运行时,如果某一方面被应用于方法?应用于、方面、方法、PostSharp

2023-09-04 10:54:08 作者:世界奇葩〃

我采取一个PostSharp方面库。 假设我们有将应用于一些方法和将不被应用于其他的方面。 我需要,我可以在运行时使用一些机制来知道是否一个方面被应用于方法

I'm implementing a PostSharp aspect library. Suppose we have an aspect that will be applied for some methods and won't be applied for the others. I need some mechanism that I can use at runtime to know if an aspect was applied to a method.

什么样的​​方法可以采取以确定在运行时某些方面是否被应用到给定一个特定的方法 System.Reflection.MethodBase

What approaches could be taken to determine at runtime whether or not certain aspect was applied to a particular method given by a System.Reflection.MethodBase?

这是进入我脑海的第一个解决方案是让PostSharp标记每一个已被修改通过这方面有一个自定义的属性附加伤害的方法,并使用 methodBase.CustomAttributes 在运行时。

The first solution that comes into my head is to make PostSharp marking every method that has been modified by this aspect with a custom atribute and use methodBase.CustomAttributes at runtime.

这是该问题的解决方案? 我的意思是,也许已经有一个现成使用的或更好的解决方案在PostSharp。

Is this the right solution for the problem? I mean maybe there already is a ready-to-use or more elegant solution in PostSharp.

另外,请考虑到preferred是不需要付费的PostSharp许可,因为免费社区版就足够让我当前项目的解决方案。 然而,这将是非常intresting基于支付PostSharp功能也共同商讨解决方案。

Also, please take into account that preferred is a solution that doesn't require a paid PostSharp license since Free Community Edition is enough for my current project. However, it would be very intresting to discuss solutions based on paid PostSharp functionality too.

推荐答案

当你添加一个方法层次方面(如的 OnExceptionAspect )作为类的属性或装配水平,PostSharp 的多播 该属性在类/组件的所有适用的方法。在下一阶段的纵横变换的每个方法与属性和本身被删除属性

When you're adding a method-level aspect (e.g. OnExceptionAspect) as an attribute on the class or the assembly level, PostSharp multicasts this attribute to all the applicable methods in that class/assembly. At the next stage the aspect transforms each method with the attribute and the attribute itself is removed.

您可以告诉PostSharp保持所有方面的属性由 MulticastAttributeUsageAttribute.PersistMetaData 属性设置为的真正的。 href="http://doc.postsharp.net/t_postsharp_extensibility_multicastattributeusageattribute" rel="nofollow"> [MulticastAttributeUsage] 属性必须被应用到