2012-06-11 65 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方法實際限制應用到特定的類型(在編譯時完成)。 –