在 for 循环中检测到无法访问的代码
本文关键字:访问 代码 for 循环 检测 | 更新日期: 2023-09-27 18:31:29
我试图找出一个数字是否是素数。但是我遇到了"检测到无法访问的代码"的错误,我认为这会影响"并非所有代码路径都返回值"的错误。该错误似乎发生在 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;
}
}
"
检测到无法访问的代码"意味着某些代码永远无法执行。 考虑:
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!
}
您的代码有两个问题:
-
您在 for 循环中具有
return true
(在任何条件之外)。由于return
立即退出函数(将控制权返回给调用方),因此for
循环的i++
语句将永远不会被执行(因此您的错误)。您可能打算将其置于 for 循环之外。
循环 中的另一个问题是不能保证循环执行。如果传递的
n
为 2 或更少,您将完全跳过循环,在这种情况下没有 return 语句。这是不允许的(因为您始终需要从非 void 函数返回一个值),因此会出现编译器错误。
下面是如何使用 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;