簡體   English   中英

在 for 循環中檢測到無法訪問的代碼

[英]Unreachable code detected in the for loop

我試圖找出一個數字是否是質數。 但是我遇到了“檢測到無法訪問的代碼”的錯誤,我認為這會影響“並非所有代碼路徑都返回一個值”的錯誤。 該錯誤似乎發生在 i++ 的 for 循環中。 誰能幫幫我嗎?

static void Main(string[] args)
    {
        Console.WriteLine(isPrime(10));
    }

    public static bool isPrime(int n)
    {
        for (int i = 2; i < n; i++)
        {
            if (n % i == 0)
            {
                return false;
            }
            return true;
        }
    }

“Unreachable code detected”意味着某些代碼永遠無法執行。 考慮:

int something()
{
  if (true)
    return 1;
  else
    return 2; //Obviously we can never get here
}

“並非所有代碼路徑都返回一個值”意味着您已經定義了一個具有返回值的方法(例如您的示例中的“bool”)並且該方法可以通過某種方式在不返回值的情況下執行。

考慮:

int something(bool someBool)
{
  if (someBool)
    return 1;
  //if someBool == false, then we're not returning anything.  Error!
}

您的代碼有兩個問題:

  1. 您在 for 循環內(在任何條件之外) return true 因為return立即退出 function(將控制權返回給調用者), for循環的i++語句將永遠不會執行(因此是您的錯誤)。 您可能打算將其置於 for 循環之外。

  2. 在循環中的另一個問題是循環不能保證執行 如果傳遞的n為 2 或更小,您將完全跳過循環,並且在這種情況下沒有 return 語句。 這是不允許的(因為你總是需要從非空函數返回一個值)所以你會得到一個編譯器錯誤。

下面是一個示例,說明如何使用 for 循環和嵌入式 If 條件獲得此返回值。

private bool WinOneLevelOne()
{
    //For loop to check all the items in the winOne array.
    for (int i = 0; i < winOne.Length; i++)
    {
        //If statement to verify that all the gameobjects in the array are yellow.
        if (winOne[i].gameObject.GetComponent<MeshRenderer>().material.color != Color.yellow)
        {
            //Keeps the boolean at false if all the gameobjects are not yellow.
            return false;
        }
    }
    return true;

暫無
暫無

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

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