简体   繁体   English

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

[英]Verbatim string containing “#” recognized as a preprocessor directive

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

If DEBUG is defined the above code builds without error using Visual Studio 2017. 如果定义了DEBUG,则以上代码将使用Visual Studio 2017正确构建。

If DEBUG is not defined, the build fails with this error: 如果未定义DEBUG,则构建将失败,并显示以下错误:

error CS1024: Preprocessor directive expected 错误CS1024:预期的预处理程序指令

The issue has been reported to the C# language design community here . 该问题已在此处报告给C#语言设计社区。

I can work around the problem by using non-verbatim strings: 我可以通过使用非普通字符串来解决此问题:

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

In my particular use case I would rather keep my strings verbatim. 在我的特定用例中,我宁愿保持原样。 Is there a different - possibly better - way to work around this problem? 是否有其他(可能更好)的方法来解决此问题?

Obviously there is no way to avoid this problem as it is, unless maybe its your VS. 显然,没有办法避免这个问题,除非它是您的VS。

However if its giving yuo problems you could try using StringBuilder , it may give you a more consistent look 但是,如果它给您带来了问题,您可以尝试使用StringBuilder ,它可能会给您更一致的外观

#if DEBUG

    Var sb = new StringBuilder();

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

#endif

If you can't go through, then go around. 如果您无法通过,那就四处走走。

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

The compiler will not warn about unused constants, nor (I hope) will any overzealous static analysers. 编译器不会警告未使用的常量,也不会(我希望)任何过分热情的静态分析器。 As an added benefit (?) you get to explain what the verbatim string actually represents. 作为附加的好处(?),您可以解释逐字字符串实际代表的含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM