7

I suppose the easiest way to explain is by a contrived example:

public static int Fail() {
    var b = true;
    if (b) {
        return 0;
    }
}

This code will not compile, and gives the error "not all code paths return a value," while we humans can clearly see that it does. I DO understand why. My question is what should be done to remedy the situation. It could be something like this:

public static int Fail() {
    var b = true;
    if (b) {
        return 0;
    }
    throw new ApplicationException("This code is unreachable... but here we are.");
}

But it all just seems rather silly. Is there a better way? Again, this code is a contrived example (and can be reduced to return 0). My actual code is massive and complex, but does logically (by mathematical proof) return a value before trying to exit.

4

6 回答 6

8

C# 代码流分析是有限的,正如您的示例指出的那样,在某些情况下所有路径都返回但编译器无法检测到它。在这些情况下,抛出异常是可接受的补救措施。

我不会使用返回默认值来修复此错误。您在假设该行永远不会违反编译器的建议的情况下进行操作。考虑一下您的分析是错误的,执行可以继续到方法的末尾。如果您返回一个默认值,那么您将没有任何问题的迹象。该方法只会返回错误数据。抛出异常会让问题很明显。

但是在这些情况下,我的偏好是简单地重写代码,以便编译器可以看到所有路径都终止了。一般来说,我发现如果方法太复杂以至于编译器无法遵循它,那么在我之后拿起代码的人也将无法遵循它。

于 2013-08-24T22:57:07.937 回答
1

编译器不会执行复杂的数学过程来确保您返回一个值,在这方面它是一个相对愚蠢的野兽。

如果你确定你的假设,只需return 0;在最后添加一条说明现实的评论,它永远不会实现。

当然,任何可以保证最终条件为真的代码都可以删除条件,正如您已经说过的那样。即使对于复杂的情况,这在数学上也是正确的。因此,您可以重构代码以考虑到这一点,而不会产生多余的回报。

于 2013-08-24T23:00:54.027 回答
1

我认为你目前的做法是正确的。在方法结束时返回默认值是有风险的,因为如果您的逻辑中有流程,则可能会到达该指令,这可能会产生意想不到的后果。如果你抛出一个异常,它会给你一个检测错误的机会。

于 2013-08-24T23:14:11.133 回答
0

通常有几类程序员:

  1. 他们谁回来了。
  2. 他们只在函数/方法结束时返回。

第一种方法:

public static int Fail() {
  var b = true;
  if (b)
    return 0;

  return 1;
}

我通常更喜欢第二种方法,因为它更容易快速查看函数/方法返回的位置。

public static int Fail() {
  var b = true;
  var returnValue = 1:
  if (b)
    returnValue = 0;

  return returnValue;
}
于 2013-08-24T23:00:54.043 回答
0

答案真的很晚,但我可以想象一个函数不知道返回什么的场景:

1)使用调试器逐步运行

2) 跨步var b = true;

3)if (b) {到达时,放入b = false手表。它会返回false和分配b = false

4)越过(越过if

5) 到达函数结束,没有返回

从这个角度来说,return显然是需要的。

于 2017-01-21T09:10:26.057 回答
0

我有这样的代码并以这种方式修复它。看你的例子:

public static int Fail() {
    var b = true;
    if (b) {
        return 0;
    }
    throw new ApplicationException("This code is unreachable... but here we are.");
}

会成为

public static int Fail() {
    var b = true;
    if (!b) {
        throw new ApplicationException("This code is unreachable... but here we are.");
    }
    return 0;
}

这将消除编译器警告,逻辑上仍然相同,实际上代码更简洁。

于 2018-03-21T14:23:58.867 回答