Multiline string literal in C#

后端 未结 13 1776
梦谈多话
梦谈多话 2020-11-22 11:15

Is there an easy way to create a multiline string literal in C#?

Here\'s what I have now:

string query = \"SELECT foo, bar\"
+ \" FROM table\"
+ \" W         


        
13条回答
  •  攒了一身酷
    2020-11-22 11:47

    Why do people keep confusing strings with string literals? The accepted answer is a great answer to a different question; not to this one.

    I know this is an old topic, but I came here with possibly the same question as the OP, and it is frustrating to see how people keep misreading it. Or maybe I am misreading it, I don't know.

    Roughly speaking, a string is a region of computer memory that, during the execution of a program, contains a sequence of bytes that can be mapped to text characters. A string literal, on the other hand, is a piece of source code, not yet compiled, that represents the value used to initialize a string later on, during the execution of the program in which it appears.

    In C#, the statement...

     string query = "SELECT foo, bar"
     + " FROM table"
     + " WHERE id = 42";
    

    ... does not produce a three-line string but a one liner; the concatenation of three strings (each initialized from a different literal) none of which contains a new-line modifier.

    What the OP seems to be asking -at least what I would be asking with those words- is not how to introduce, in the compiled string, line breaks that mimick those found in the source code, but how to break up for clarity a long, single line of text in the source code without introducing breaks in the compiled string. And without requiring an extended execution time, spent joining the multiple substrings coming from the source code. Like the trailing backslashes within a multiline string literal in javascript or C++.

    Suggesting the use of verbatim strings, nevermind StringBuilders, String.Joins or even nested functions with string reversals and what not, makes me think that people are not really understanding the question. Or maybe I do not understand it.

    As far as I know, C# does not (at least in the paleolithic version I am still using, from the previous decade) have a feature to cleanly produce multiline string literals that can be resolved during compilation rather than execution.

    Maybe current versions do support it, but I thought I'd share the difference I perceive between strings and string literals.

    UPDATE:

    (From MeowCat2012's comment) You can. The "+" approach by OP is the best. According to spec the optimization is guaranteed: http://stackoverflow.com/a/288802/9399618

提交回复
热议问题