C#中的多行字符串文字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1100260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiline string literal in C#
提问by Chet
Is there an easy way to create a multiline string literal in C#?
有没有一种简单的方法可以在 C# 中创建多行字符串文字?
Here's what I have now:
这是我现在所拥有的:
string query = "SELECT foo, bar"
+ " FROM table"
+ " WHERE id = 42";
I know PHP has
我知道 PHP 有
<<<BLOCK
BLOCK;
Does C# have something similar?
C# 有类似的东西吗?
采纳答案by John Rasch
You can use the @
symbol in front of a string
to form a verbatim string literal:
您可以使用@
a 前面的符号string
来形成逐字字符串文字:
string query = @"SELECT foo, bar
FROM table
WHERE id = 42";
You also do not have to escape special characterswhen you use this method, except for double quotes as shown in Jon Skeet's answer.
使用此方法时,您也不必转义特殊字符,除了 Jon Skeet 的回答中所示的双引号。
回答by Jon Skeet
It's called a verbatim string literalin C#, and it's just a matter of putting @ before the literal. Not only does this allow multiple lines, but it also turns off escaping. So for example you can do:
它在 C# 中称为逐字字符串文字,只需将 @ 放在文字之前即可。这不仅允许多行,而且还关闭转义。例如,您可以执行以下操作:
string query = @"SELECT foo, bar
FROM table
WHERE name = 'a\b'";
This includes the line breaks (using whatever line break your source has them as) into the string, however. For SQL, that's not only harmless but probably improvesthe readability anywhere you see the string - but in other places it may not be required, in which case you'd either need to not use a multi-line verbatim string literal to start with, or remove them from the resulting string.
但是,这包括字符串中的换行符(使用您的源代码中的任何换行符)。对于 SQL,这不仅无害,而且可能会提高您看到字符串的任何地方的可读性 - 但在其他地方可能不需要它,在这种情况下,您要么不需要使用多行逐字字符串文字开始,或从结果字符串中删除它们。
The only bit of escaping is that if you want a double quote, you have to add an extra double quote symbol:
唯一的转义是如果你想要一个双引号,你必须添加一个额外的双引号符号:
string quote = @"Jon said, ""This will work,"" - and it did!";
回答by Martin Clarke
One other gotcha to watch for is the use of string literals in string.Format. In that case you need to escape curly braces/brackets '{' and '}'.
另一个需要注意的问题是在 string.Format 中使用字符串文字。在这种情况下,您需要转义大括号/方括号“{”和“}”。
// this would give a format exception
string.Format(@"<script> function test(x)
{ return x * {0} } </script>", aMagicValue)
// this contrived example would work
string.Format(@"<script> function test(x)
{{ return x * {0} }} </script>", aMagicValue)
回答by dav_i
The problem with using string literal I find is that it can make your code look a bit "weird" because in order to not get spaces in the string itself, it has to be completely left aligned:
我发现使用字符串文字的问题是它会使您的代码看起来有点“奇怪”,因为为了不在字符串本身中获得空格,它必须完全左对齐:
var someString = @"The
quick
brown
fox...";
Yuck.
哎呀。
So the solution I like to use, which keeps everything nicely aligned with the rest of your code is:
所以我喜欢使用的解决方案是:
var someString = String.Join(
Environment.NewLine,
"The",
"quick",
"brown",
"fox...");
And of course, if you just want to logically split up lines of an SQL statement like you are and don't actually need a new line, you can always just substitute Environment.NewLine
for " "
.
当然,如果你只是想在逻辑上分割的SQL语句的线条像你和实际上并不需要一个新的线,你永远可以替代Environment.NewLine
的" "
。
回答by RobertHana
I haven't seen this, so I will post it here (if you are interested in passing a string you can do this as well.) The idea is that you can break the string up on multiple lines and add your own content (also on multiple lines) in any way you wish. Here "tableName" can be passed into the string.
我还没有看到这个,所以我会把它贴在这里(如果你有兴趣传递一个字符串,你也可以这样做。)这个想法是你可以把字符串分成多行并添加你自己的内容(也在多行上)以您希望的任何方式。这里可以将“tableName”传递到字符串中。
private string createTableQuery = "";
void createTable(string tableName)
{
createTableQuery = @"CREATE TABLE IF NOT EXISTS
["+ tableName + @"] (
[ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[Key] NVARCHAR(2048) NULL,
[Value] VARCHAR(2048) NULL
)";
}
回答by rattray
If you don't want spaces/newlines, string addition seems to work:
如果您不想要空格/换行符,字符串添加似乎有效:
var myString = String.Format(
"hello " +
"world" +
" i am {0}" +
" and I like {1}.",
animalType,
animalPreferenceType
);
// hello world i am a pony and I like other ponies.
You can run the above hereif you like.
如果您愿意,可以在此处运行以上内容。
回答by Heliac
As a side-note, with C# 6.0 you can now combine interpolated strings with the verbatim string literal:
作为旁注,使用 C# 6.0,您现在可以将内插字符串与逐字字符串文字组合起来:
string camlCondition = $@"
<Where>
<Contains>
<FieldRef Name='Resource'/>
<Value Type='Text'>{(string)parameter}</Value>
</Contains>
</Where>";
回答by nassimlouchani
You can use this two methods :
您可以使用这两种方法:
private static String ReverseString(String str)
{
int word_length = 0;
String result = "";
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ' ')
{
result = " " + result;
word_length = 0;
}
else
{
result = result.Insert(word_length, str[i].ToString());
word_length++;
}
}
return result;
}
//NASSIM LOUCHANI
public static string SplitLineToMultiline(string input, int rowLength)
{
StringBuilder result = new StringBuilder();
StringBuilder line = new StringBuilder();
Stack<string> stack = new Stack<string>(ReverseString(input).Split(' '));
while (stack.Count > 0)
{
var word = stack.Pop();
if (word.Length > rowLength)
{
string head = word.Substring(0, rowLength);
string tail = word.Substring(rowLength);
word = head;
stack.Push(tail);
}
if (line.Length + word.Length > rowLength)
{
result.AppendLine(line.ToString());
line.Clear();
}
line.Append(word + " ");
}
result.Append(line);
return result.ToString();
}
In the SplitLineToMultiline() , you need to define the string you want to use and the row length , it's very simple . Thank you .
在 SplitLineToMultiline() 中,需要定义要使用的字符串和行长,非常简单。谢谢你 。
回答by Carvo Loco
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.
我知道这是一个古老的话题,但我来到这里可能带着与 OP 相同的问题,看到人们如何不断误读它令人沮丧。或者也许我误读了它,我不知道。
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...
在 C# 中,语句...
string query = "SELECT foo, bar"
+ " FROM table"
+ " WHERE id = 42";
... does notproduce 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 withoutintroducing 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++.
OP 似乎在问什么 - 至少我会用这些词问什么 - 不是如何在编译后的字符串中引入模仿源代码中的换行符,而是如何长时间分解, 源代码中的单行文本,而不会在已编译的字符串中引入中断。并且不需要延长的执行时间,花在连接来自源代码的多个子字符串上。就像 javascript 或 C++ 中多行字符串文字中的尾随反斜杠一样。
Suggesting the use of verbatim strings, nevermind StringBuilder
s, String.Join
s 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.
建议使用逐字字符串、没关系StringBuilder
s、String.Join
s 甚至带有字符串反转的嵌套函数等等,这让我认为人们并没有真正理解这个问题。或者我不明白。
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 literalsthat can be resolved during compilation rather than execution.
据我所知,C# 没有(至少在我仍在使用的旧石器时代版本,从前十年开始)具有干净地生成多行字符串文字的功能,可以在编译而不是执行期间解析。
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
(来自 MeowCat2012 的评论)你可以。OP 的“+”方法是最好的。根据规范保证优化:http: //stackoverflow.com/a/288802/9399618
回答by vovkas
You can use @and "".
您可以使用@和""。
string sourse = @"{
""items"":[
{
""itemId"":0,
""name"":""item0""
},
{
""itemId"":1,
""name"":""item1""
}
]
}";