#if DEBUG 和 return 语句 - 无法访问的代码警告

#if DEBUG and return statements - Unreachable code warning

我正面临这段代码:

#if DEBUG
return thisVariable;
#endif
return thatVariable; //<-- warning CS0162 here

它工作正常,除了我在第二个 return 语句中收到警告代码无法访问。尽管有警告,当 运行 程序处于发布模式时,代码实际上是非常容易访问的。

为什么我会收到此警告?

如果您正在执行定义了 DEBUG 符号的构建,那么编译器将对您的代码执行静态分析假设第一个 return 生效并且不排除。所以你的代码将被视为:

return thisVariable;
return thatVariable;

在这种情况下,很明显第二个 return 语句不会在这样的构建中达到。当您切换到未定义 DEBUG 的构建配置时,您应该不会看到警告。

考虑使用 #else (docs) 以避免在定义 DEBUG 时使用第二个 return 语句。

还有来自 here 的相关花絮:

Although the compiler does not have a separate preprocessor, the directives described in this [C# Preprocessor Directives] section are processed as if there were one.

换句话说,C# 编译器的静态分析并不知道预处理器指令;它们在那个时候已经被处理过,静态分析只看到从预处理阶段得到的代码。