【问题标题】:How to Intercept, skip method execution and continue with the rest of the stack如何拦截、跳过方法执行并继续堆栈的其余部分
【发布时间】:2016-03-18 03:35:04
【问题描述】:

有没有办法拦截方法调用,查找条件并跳过执行?该方法不返回任何内容,我想将其视为已成功完成并继续使用堆栈的其余部分执行。

public IMessageSink NextSink {
    get { return m_next; }
}

public IMessage SyncProcessMessage(IMessage msg) {
    if (//some condition is met) {
        // should skip the method execution
    } else {
        IMessage returnMethod = m_next.SyncProcessMessage(msg);
        return returnMethod;
    }
}

【问题讨论】:

  • 什么都不返回return;
  • 仅供参考,如果您的条件恰好是检查 m_next == null,看起来很可能,那么您可以在 C# 6 中的一行中执行此操作:return m_next?.SyncProcessMessage(msg);

标签: c# aop interceptor


【解决方案1】:

return 语句终止方法的执行。在这种情况下,您应该使用return null,因为SyncProcessMessage() 必须返回IMessage 的值

public IMessage SyncProcessMessage(IMessage msg) {
    if (//some condition is met) {
        return null;
    } else {
        IMessage returnMethod = m_next.SyncProcessMessage(msg);
        return returnMethod;
    }
}

或类似的东西:

public IMessage SyncProcessMessage(IMessage msg) {
    IMessage returnMethod  = null;
    if (! //not some condition is met) {
        returnMethod = m_next.SyncProcessMessage(msg);            
    }
    return returnMethod;
}

【讨论】:

  • return null 是抛出异常。异常:System.Runtime.Remoting.RemotingException:使用意外类型的消息调用该方法。结果 StackTrace:在 System.Runtime.Remoting.Proxies.RemotingProxy.CallProcessMessage(IMessageSink ms,IMessage reqMsg,ArrayWithSize proxySinks,线程 currentThread,上下文 currentContext,布尔 bSkippingContextChain)
  • @Kiran 当然,你应该在你打电话给SyncProcessMessage()的地方抓住它
猜你喜欢
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-05
相关资源
最近更新 更多