簡體   English   中英

從調用方法返回

[英]Return from the calling method

我有方法

public void x()
{
    y();
    z();
}

public void y()
{
    if(some condition) return;
    some code...
}

public void z()
{
    somecode...
}

我知道,如果滿足somecondition條件,將返回method y()中的return語句,而不執行該方法中的任何其他操作,並將返回到method x()並執行method z() 但是有沒有辦法從method x()返回而不執行method z()呢?

我無法更改任何約束或編輯method y

使y()返回某種代碼以讓x()知道是否調用z()

public void x()
{
    if (y())
    {
        z();
    }
}

// Return true if processing should continue.
//
public bool y()
{
    if(some condition) return false;
    some code...
    return true;
}

public void z()
{
    somecode...
}

一種選擇是從y()返回bool值。

public void x()
{
    var isValidY = y();

    if (isValidY)
        z();
}

public bool y()
{
    if(some condition) return false;

    // some code...
    return true;
}

public void z()
{
    // some code...
}

如果您不能更改y()則必須接受注釋中剩下的建議Enigmativity,並重復由some condition表示的邏輯:

public void x()
{
    y();
    if (some condition) return;
    z();
}

public bool y()
{
    if (some condition) return;
    // some code...
}

如果您不能更改方法簽名,請創建一個全局標志變量:

private bool shouldContinue = true;

public void x()
{
    y();

    if(shouldContinue)
        z();
}

public void y()
{
    if(some condition)
    {
        shouldContinue = false;
        return;
    }
    some code...
}

public void z()
{
    somecode...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM