【问题标题】:Call alternative method in class using postsharp使用 postsharp 在课堂上调用替代方法
【发布时间】:2012-06-11 22:21:40
【问题描述】:

我希望能够使用PostSharp 在我截获的类上调用不同的方法。

假设我的PostSharp 方面有以下方法:

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        if (!m_featureToggle.FeatureEnabled)
        {
            base.OnInvoke(args);
        }
        else
        {
            var instance = args.Instance;
            instance.CallDifferentMethod(); //this is made up syntax
        }  
    }

CallDifferentMethod() 是类中另一个被拦截的方法。我可以做一些反射魔法来获得我想要被调用的名称,但我不知道如何在类的 this 实例上调用该方法。我不想启动类的新实例

有什么建议吗?

【问题讨论】:

    标签: c# aop postsharp


    【解决方案1】:

    您是否将 args.Instace 转换为您的类型?根据您写的内容,我想您的“FeatureEnabled”应该通过接口定义。

    public interface IHasFeature
    {
      bool IsFeatureEnabled { get; set; }
      void SomeOtherMethod();
    }
    

    然后使用

    ((IHasFeature)args.Instance).SomeOtherMethod(); 
    

    然后将方面应用到该接口。

    [assembly: MyApp.MyAspect(AttributeTargetTypes = "MyApp.IHasFeature")]
    

    或者直接在界面上

    [MyAspect]
    public interface IHasFeature
    

    更新:糟糕,盖尔是对的。对于那个很抱歉。使用 CompileTimeValidate 方法在编译时限制方面。

    public override bool CompileTimeValidate(System.Reflection.MethodBase method)
            {
                bool isCorrectType = (Check for correct type here)
                return isCorrectType;
            }
    

    更多信息请看我的帖子http://www.sharpcrafters.com/blog/post/Day-9-Aspect-Lifetime-Scope-Part-1.aspx

    【讨论】:

    • Dustin 是正确的关于将演员转换为通用界面。另一种方法是“动态”的案例。但是,将方面应用到界面并不会将方面“限制”到此界面。它只是“应用”它。应使用 CompileTimeValidate 进行限制。
    • 糟糕,@GaelFraiteur 是对的,使用 CompileTimeValidate 方法将应用程序实际限制为特定类型(在编译时完成)。
    猜你喜欢
    • 2011-12-13
    • 1970-01-01
    • 2019-05-13
    • 2015-03-31
    • 2019-01-03
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多