2012-06-11 64 views
4

我希望能够通过使用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()是已截获类中的另一种方法。我可以做一些反思魔术得到什么,我想叫这个名字,但我不能工作了如何调用该方法上这个类的实例。我不想加速旋转类

任何建议的新实例?

回答

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

+0

达斯汀是正确的关于强制转换为通用接口。另一种方法是将案例变为“动态”。但是,将界面应用到界面并不会将界面“限制”到该界面。它只是“应用”它。限制应该使用CompileTimeValidate完成。 –

+0

糟糕,@GaelFraiteur是正确的,使用CompileTimeValidate方法实际限制应用到特定的类型(在编译时完成)。 –