包含“#”的逐字字符串被识别为预处理器指令

Verbatim string containing "#" recognized as a preprocessor directive

#if DEBUG
    string s = @"
# text";
#endif

如果定义了 DEBUG,上述代码使用 Visual Studio 2017 构建时没有错误。

如果未定义 DEBUG,构建将失败并出现此错误:

error CS1024: Preprocessor directive expected

已将此问题报告给 C# 语言设计社区 here

我可以使用非逐字字符串来解决这个问题:

#if DEBUG
    string s = "\n" +
"# text";
#endif

在我的特定用例中,我宁愿逐字保留我的字符串。 是否有其他(可能更好)的方法来解决此问题?

显然没有办法避免这个问题,除非它可能是你的 VS。

但是,如果它给您带来问题,您可以尝试使用 StringBuilder,它可能会让您看起来更一致

#if DEBUG

    Var sb = new StringBuilder();

    S.AppendLine("rah");
    S.AppendLine("");
    S.AppendLine("# Text");
    S.AppendLine("# Blah");

#endif

过不去就绕过去

const string shellScript = @"
# text";
#if DEBUG
    string s = shellScript;
#endif

编译器不会对未使用的常量发出警告,(我希望)任何过分热心的静态分析器也不会。作为一个额外的好处 (?),您可以解释逐字字符串实际代表什么。