PostSharp 如何在运行时知道某个方面是否应用于方法? [英] PostSharp How to know at runtime if a certain aspect was applied to a method?

查看:20
本文介绍了PostSharp 如何在运行时知道某个方面是否应用于方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个 PostSharp 方面库,但找不到以下问题的解决方案.

I'm implementing a PostSharp aspect library and can't find out a solution to the following problem.

假设我们有一个方面将应用于某些方法而不会应用于其他方法.我需要一些可以在运行时使用的机制来了解某个方面是否应用于方法.具体来说,在运行时确定某个方面是否应用于由 System.Reflection.MethodBase 给出的特定方法的推荐方法是什么?

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 whether an aspect was applied to a method. Specifically, what is the recommended way to determine at runtime whether certain aspect was applied to a particular method given by a System.Reflection.MethodBase?

我想到的第一个解决方案是让 PostSharp 使用自定义属性标记每个已被此方面修改的方法,并在运行时使用 methodBase.CustomAttributes.这是解决问题的正确方法吗?或者 PostSharp 中已经有现成的或更优雅的解决方案.

The first solution that comes into my head is to make PostSharp mark every method that has been modified by this aspect with a custom atribute and use methodBase.CustomAttributes at runtime. Is this the right solution for the problem? Or maybe there already is a ready-to-use or more elegant solution in PostSharp.

另外,请注意首选解决方案不需要付费 PostSharp 许可证,因为免费社区版足以满足我当前的项目.无论如何,讨论基于付费 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. Anyway, it would be very intresting to discuss solutions based on paid PostSharp functionality too.

推荐答案

当您添加方法级方面时(例如 OnExceptionAspect) 作为类或程序集级别的属性,PostSharp multicasts 这个属性到所有该类/程序集中的适用方法.在下一阶段,方面用属性转换每个方法,然后删除属性本身.

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.

您可以通过将 MulticastAttributeUsageAttribute.PersistMetaData 属性设置为 true<来告诉 PostSharp 保留所有方面属性.[MulticastAttributeUsage] 属性必须应用于您的方面类.

You can tell PostSharp to keep all the aspect attributes by setting the MulticastAttributeUsageAttribute.PersistMetaData property to true. The [MulticastAttributeUsage] attribute must be applied to your aspect class.

[MulticastAttributeUsage( PersistMetaData = true )]
public class MyAspect : OnExceptionAspect
{
    // ...
}

现在您可以在 MethodBase.CustomAttributes 中查找 MyAspect 以确定方面是否已应用于当前方法.

Now you can look for MyAspect in MethodBase.CustomAttributes to determine whether the aspect has been applied to the current method.

这篇关于PostSharp 如何在运行时知道某个方面是否应用于方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆