【问题标题】:How to apply a postsharp aspect to just methods defined in child classes of a given class?如何将 postsharp 方面应用于给定类的子类中定义的方法?
【发布时间】:2015-01-06 18:37:42
【问题描述】:

我可以指定 PostSharp 方面仅应用于给定类的子类的所有公共方法吗?

我的意思是,我有 ClassA 并希望将 OnMethodBoundaryAspect 仅应用于从 ClassA 继承的类中定义的公共方法。

【问题讨论】:

    标签: c# aop postsharp aspect aspects


    【解决方案1】:

    您需要使用MulticastAttributeAttributeInheritance 属性来控制该行为。

    • MulticastInheritance.None 是默认行为。派生类不继承切面。
    • MulticastInheritance.Strict 使派生类继承基类成员的方面,即覆盖方法。
    • MulticastInheritance.Multicast 使派生类完全继承切面,即好像您在派生类上指定了切面。

    然后,您需要使用MulticastAttribute 中的AttributeTargetMemberAttributes 来指定应将属性应用于哪些成员。在您的情况下,这将是 AttributeTargetMemberAttributes = MulticastAttributes.Public

    最后,您需要强制 PostSharp 不将该属性应用到基类本身,您可以在另一个属性实例上使用AttributeExclude 属性来在特定情况下禁用方面。

    因此,“仅对给定类的子类的所有公共方法”将满足以下条件:

    [MyAspect(AttributeInheritance = MulticastInheritance.Multicast, AttributeTargetMemberAttributes = MulticastAttributes.Public)]
    [MyAspect(AttributeExclude = true)]
    public class ClassA
    {
        //...
    }
    

    请注意,这是编译时行为,您需要在从基类派生的所有项目上运行 PostSharp,以使其按预期工作。如果您从没有被 PostSharp 增强的项目中的类派生,则不会继承任何方面的行为。

    【讨论】:

    • 感谢您的评论 Daniel,但至少我误解了您所说的,没有这些选项我得到了我想要的:将属性应用于 " 仅应用于类中定义的公共方法继承自”给定类
    • @gsc-frank 这个问题并不完全清楚。我已经更新了我的答案,以更接近它的预期含义(希望如此)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    相关资源
    最近更新 更多