【发布时间】:2011-02-25 01:27:26
【问题描述】:
我有一些代码需要在调试和发布模式下略有不同。它有一个名为PrettyPrint 的常量,在某些模式下设置为true,在其他模式下设置为false,我有时会更改它们。
#if DEBUG
public const bool PrettyPrint = true;
#else
public const bool PrettyPrint = false;
#endif
// ...snip...
string start, end, comma, innerIndentation;
if (Printer.PrettyPrint) {
innerIndentation = indentation + " ";
start = "[\n";
end = indentation + "]";
comma = ",\n" + innerIndentation;
} else {
innerIndentation = "";
start = "[";
end = "]";
comma = ",";
}
// Then do some prints using the initialized strings as constants
这很好用,编译器足够聪明,可以优化if。但是,我收到了一个烦人的警告:
warning CS0162: Unreachable code detected
有没有办法在不执行以下任何操作的情况下避免此警告:
- 直接在代码中使用
#if- 因为它使那部分代码非常难看,我想尽可能避免#ifs。 - 在其他情况下禁止 CS0162 - 因为我发现该警告对于查找损坏的代码非常有用。
我如何使用#if DEBUG 语句而不让 IDE 相信后面的所有代码都无法访问?
【问题讨论】:
-
将 const 替换为 readonly。
-
编译器是不是被骗了?我没有看到任何无法访问的代码
-
@Nicklammort,编译器注意到
Printer.PrettyPrint是const,因此永远不会改变。即if语句将始终评估为true,这意味着else部分将无法访问(反之亦然,当不处于调试模式时) -
@Nicklamor: DEBUG 在编译时设置。因此,对于给定的编译,PrettyPrint 将始终为真或始终为假。
-
“执行之间”是什么意思?无论您运行代码多少次,该常量将始终为真或始终为假,直到使用不同的 DEBUG 标志重新编译代码。无论哪种方式,其中一个代码块都无法访问,编译器警告您这是完全合适的。
标签: c# warnings suppress-warnings compiler-directives