这个问题在这里已经有了答案:
.NET compiler and "Not all code paths return a value"
(5 个回答)
3年前关闭。
编译器提示以下代码片段不会总是返回。我已经检查过了,没有发现问题。
private int MyFunction(int b)
{
int result = -1;
while (result != 1)
{
result = MySmallFunction(out var x);
if (result == 1)
{
return x;
}
}
}
private int MySmallFunction(out int x)
{
x = 1;
return 1;
}
MySmallFunction
做东西并返回一个代码,1
表示成功,其余为错误码。如果返回
1
,这意味着 out int x
有一个值(value)。如果返回值不是
1
(错误代码),然后我想重试。如果
MySmallFunction
永不返回 1
,应用程序应该永远卡在一个循环中。这对编译器来说应该不是问题。
最佳答案
我将函数重写为:
private int MyFunction()
{
int result = -1;
int x = int.MinValue;
while (result != 1)
{
result = MySmallFunction(out x);
}
return x;
}
private int MySmallFunction(out int x)
{
x = 1;
return 1;
}
现在
x
只有在 MySmallFunction
时才会返回返回状态码 1
.
关于c# - 并非所有代码路径都返回带有 while 循环的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51841007/