CS0161: 不是所有代码路径 return 一个值
CS0161: not all code paths return a value
在下面的 C# 代码片段中,我循环遍历所有整数,直到 x,并在找到 x 的除数后立即 return。
class Program
{
static void Main(string[] args)
{
}
static int LowestDivisor(int x)
{
if (x < 0)
x *= -1;
if (x == 0 || x == 1)
return -1;
for (int i = 2; i <= x; i++)
{
if (x % i == 0)
{
return i;
}
}
}
}
}
我看不出是什么原因导致编译器给出错误 CS0161: not all code paths return a value
。对于质数,for 循环的最后一次迭代 return 是质数。如果不是,除数将在较早的迭代中被 returned。因此,for all code paths
,一个值是 returned。我错了吗?
编译器不知道对于任何给定的输入,如果一个值没有在前两个 if
中捕获,它肯定会 return 在 for
循环。
它所看到的只是在某些时候有一个 for
和一个 if
里面,因为 x
的某些值将退出而没有 return 任何值。
您可以在循环后添加 return 0
或默认值,甚至 throw
一个例外。
编译器不知道 if
中的一个最终会计算为 true
。在 for
循环之后你需要一些默认的 return 值,即使它在实践中从未达到过:
static int LowestDivisor(int x)
{
if (x < 0)
x *= -1;
if (x == 0 || x == 1)
return -1;
for (int i = 2; i <= x; i++)
{
if (x % i == 0)
{
return i;
}
}
// Should never happen...
return x;
}
在下面的 C# 代码片段中,我循环遍历所有整数,直到 x,并在找到 x 的除数后立即 return。
class Program
{
static void Main(string[] args)
{
}
static int LowestDivisor(int x)
{
if (x < 0)
x *= -1;
if (x == 0 || x == 1)
return -1;
for (int i = 2; i <= x; i++)
{
if (x % i == 0)
{
return i;
}
}
}
}
}
我看不出是什么原因导致编译器给出错误 CS0161: not all code paths return a value
。对于质数,for 循环的最后一次迭代 return 是质数。如果不是,除数将在较早的迭代中被 returned。因此,for all code paths
,一个值是 returned。我错了吗?
编译器不知道对于任何给定的输入,如果一个值没有在前两个 if
中捕获,它肯定会 return 在 for
循环。
它所看到的只是在某些时候有一个 for
和一个 if
里面,因为 x
的某些值将退出而没有 return 任何值。
您可以在循环后添加 return 0
或默认值,甚至 throw
一个例外。
编译器不知道 if
中的一个最终会计算为 true
。在 for
循环之后你需要一些默认的 return 值,即使它在实践中从未达到过:
static int LowestDivisor(int x)
{
if (x < 0)
x *= -1;
if (x == 0 || x == 1)
return -1;
for (int i = 2; i <= x; i++)
{
if (x % i == 0)
{
return i;
}
}
// Should never happen...
return x;
}