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

标签 c# compiler-errors return return-value

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





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

相关文章:

c# - 响应式(Reactive)管道——如何控制并行度?

c# - 实体条目的意外 GetType() 结果

c# - 我应该在多个上下文中使用 ViewModels/模型吗?

c# - 可重复的复杂正则表达式,带点 '.' 分隔符

java - 未使用的导入不会发出警告

javascript - 'return' 没有输出所有结果

c++ - 带有两个返回语句的 std::partition

c# - 将容器对象内的所有公共(public)对象(字符串/整数/枚举)的值写入控制台

objective-c - 预期标识符 '('

c++ - C++ 中的 for_each()