使用postsharp在类中调用替代方法

时间:2012-06-11 00:20:37

标签: c# aop postsharp

我希望能够使用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()是被拦截的类中的另一种方法。我可以做一些反射魔法来获取我想要调用的名称,但是我无法弄清楚如何在类的这个实例上调用该方法。我不想启动类的新实例

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

您是否正在为您的类型投射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

相关问题