Line continue character in C#
我们有一个包含非常长字符串的变量的单元测试。
问题是如何在代码中编写它,而不会出现换行或代码难以读取的问题。
在vb中有一个行继续字符,在c中有等价物吗?
C允许在多行上拆分一个字符串,该术语称为
1 2 3 4 5 6 7 8 | string myString = @"this is a test to see how long my string can be and it can be quite long"; |
如果您正在寻找vb中的
字符串恒量
只需使用
例如
1 2 3 4 | const string myVeryLongString = "This is the opening paragraph of my long string." + "Which is split over multiple lines to improve code readability," + "but is in fact, just one long string."; |
字符串变量
注意,当使用字符串插值将值替换到字符串中时,需要在需要进行替换的每一行之前使用
1 2 3 4 | var interpolatedString = "This line has no substitutions." + $" This line uses {count} widgets, and" + $" {CountFoos()} foos were found."; |
但是,这会导致对
1 2 3 4 5 6 7 8 9 10 11 | IL_002E: ldstr "This line has no substitutions." IL_0033: ldstr " This line uses {0} widgets, and" IL_0038: ldloc.0 // count IL_0039: box System.Int32 IL_003E: call System.String.Format *** IL_0043: ldstr " {0} foos were found." IL_0048: ldloc.1 // CountFoos IL_0049: callvirt System.Func<System.Int32>.Invoke IL_004E: box System.Int32 IL_0053: call System.String.Format *** IL_0058: call System.String.Concat *** |
虽然您可以使用
1 2 3 | var interpolatedString = $@"When breaking up strings with `@` it introduces <- [newLine and whitespace here!] each time I break the string. <- [More whitespace] {CountFoos()} foos were found."; |
注入的空白很容易被发现:
1 2 3 | IL_002E: ldstr "When breaking up strings with `@` it introduces <- [newLine and whitespace here!] each time I break the string. <- [More whitespace] {0} foos were found." |
另一种选择是恢复到
1 2 3 4 | const string longFormatString = "This is the opening paragraph of my long string with {0} chars." + "Which is split over multiple lines to improve code readability," + "but is in fact, just one long string with {1} widgets."; |
然后评估如下:
1 | string.Format(longFormatString, longFormatString.Length, CountWidgets()); |
但是,考虑到格式化字符串和替换标记之间可能存在分离,这仍然很难维护。
1 2 | @"string here that is long you mean" |
但是要小心,因为
1 2 3 | @"string here and space before this text means the space is also a part of the string" |
它也会避开字符串中的内容
1 2 3 | @"c:\\folder" // c:\\folder @"c:\folder" // c:\folder "c:\\folder" // c:\folder |
相关的
- 在C中,变量名前面的@符号是什么意思?
- msdn字符串引用
您可以使用逐字文字:
1 2 3 4 | const string test = @"Test 123 456 "; |
但第1行的凹痕很难看。
您必须使用以下方法之一:
1 2 3 4 5 | string s = @"loooooooooooooooooooooooong loooooong long long long"; string s ="loooooooooong loooong" + " long long" ; |
如果声明了不同的变量,则使用以下简单方法:
1 2 3 4 5 6 7 8 | Int salary=2000; String abc="I Love Pakistan"; Double pi=3.14; Console.Writeline=salary+"/n"+abc+"/n"+pi; Console.readkey(); |