1

我有一些代码需要在调试和发布模式下略有不同。它有一个常量,在某些模式和其他模式PrettyPrint中设置为,我有时会更改它们。truefalse

#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 不相信后面的所有代码都无法访问的情况下使用语句?

4

5 回答 5

2

虽然我目前不知道如何将其应用到您的代码中,但您可能会发现它ConditionalAttribute很有帮助。您可以使用预处理器指令,但您可能必须重新编写代码。

于 2011-02-25T01:37:24.827 回答
2

您可以执行以下操作来绕过它。

Printer.PrettyPrint.Equals(true)
于 2011-02-25T12:32:16.620 回答
1

您可以更改PrettyPrint为普通字段而不是const.
您将失去编译器优化,但这无关紧要。

我很确定您也可以在readonly没有收到警告的情况下成功;尝试一下。

于 2011-02-25T01:31:38.157 回答
1

你可以试试:

innerIndentation = Printer.PrettyPrint ? indentation + " " : "";

start = Printer.PrettyPrint ? "[\n" : "[";

end = Printer.PrettyPrint ? indentation + "]" : "]";

comma = Printer.PrettyPrint ? ",\n" + innerIndentation : ",";

但如果是我,我会用一个#if #else

于 2011-02-25T01:35:00.913 回答
0

将 PrettyPrint 从 const 更改为字段。

#if DEBUG          
    public bool PrettyPrint = true;  
#else 
    public bool PrettyPrint = false;  
#endif
于 2011-02-25T02:45:35.397 回答