如何拦截,跳过方法执行并继续堆栈的其余部分

时间:2016-03-17 19:12:04

标签: c# aop interceptor

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

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;
    }
}

1 个答案:

答案 0 :(得分: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;
}