简体   繁体   中英

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.

If DEBUG is not defined, the build fails with this error:

error CS1024: Preprocessor directive expected

The issue has been reported to the C# language design community here .

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.

However if its giving yuo problems you could try using StringBuilder , it may give you a more consistent look

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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