使用postsharp在类中调用替代方法
本文关键字:方法 调用 postsharp 使用 | 更新日期: 2023-09-27 18:36: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()
是类中已被截获的另一个方法。我可以做一些反射魔法来获取我想要调用的名称,但我无法弄清楚如何在这个类实例上调用该方法。我不想启动该类的新实例
有什么建议吗?
你在施放参数吗?适合你的类型?根据你写的内容,我想你的"功能启用"应该通过一个接口来定义。
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