gpt4 book ai didi

c# - 并非所有代码路径都返回带有 while 循环的值

转载 作者:行者123 更新时间:2023-12-02 10:53:45 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com