在 C# 中,跨多个源代码行传播单行字符串文字的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1990395/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:27:55  来源:igfitidea点击:

In C#, what's the best way to spread a single-line string literal across multiple source lines?

c#stringcoding-style

提问by Matthew

Suppose that you have a lengthy string (> 80 characters) that you want to spread across multiple source lines, but don't want to include any newline characters.

假设您有一个很长的字符串(> 80 个字符),您希望将其分布在多个源代码行中,但又不想包含任何换行符。

One option is to concatenate substrings:

一种选择是连接子字符串:

string longString = "Lorem ipsum dolor sit amet, consectetur adipisicing" +
    " elit, sed do eiusmod tempor incididunt ut labore et dolore magna" +
    " aliqua. Ut enim ad minim veniam";

Is there a better way, or is this the best option?

有没有更好的方法,或者这是最好的选择?

Edit: By "best", I mean easiest for the coder to read, write, and edit. For example, if you didwant newlines, it's very easy to look at:

编辑:所谓“最佳”,我的意思是编码人员最容易阅读、编写和编辑。例如,如果您确实想要换行符,则很容易查看:

string longString =
@"Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam";

I am wondering if there is something just as clean when you don'twant newlines.

我想知道当你想要换行符时是否有同样干净的东西。

采纳答案by bobbymcr

I would use a variation of your method:

我会使用你的方法的变体:

string longString =
    "Lorem ipsum dolor sit amet, consectetur adipisicing " + 
    "elit, sed do eiusmod tempor incididunt ut labore et dolore magna " + 
    "aliqua. Ut enim ad minim veniam.";

Here I start the string on the line after the equals sign so that they all line up, and I also make sure the space occurs at the end of the line (again, for alignment purposes).

在这里,我在等号之后的行上开始字符串,以便它们全部对齐,并且我还确保空格出现在行尾(再次,出于对齐目的)。

回答by Eilon

You could use multiple consts and then combine them into one big string:

您可以使用多个常量,然后将它们组合成一个大字符串:

const string part1 = "part 1";
const string part2 = "part 2";
const string part3 = "part 3";
string bigString = part1 + part2 + part3;

The compiler will "fold" these constants into one big string anyway, so there is no runtime cost at all to this technique as compared to your original code sample.

无论如何,编译器都会将这些常量“折叠”成一个大字符串,因此与您的原始代码示例相比,这种技术根本没有运行时成本。

There are a number of advantages to this approach:

这种方法有很多优点:

  1. The substrings can be easily reused in other parts of the application.
  2. The substrings can be defined in multiple files or types, if desired.
  1. 子字符串可以很容易地在应用程序的其他部分重用。
  2. 如果需要,可以在多个文件或类型中定义子字符串。

回答by LBushkin

Your original idea is probably the easiest way to have an embedded literal string in your code.The C# compiler merges literals concatenated with +- so it's essentially equivalent to a single really long string.

您最初的想法可能是在代码中嵌入文字字符串的最简单方法。C#编译器合并文字串联起来+-因此它本质上等同于一个很长的字符串。

Another option, of course, is to externalize the string into a configuration file or a settings file. This would allow it to be both more easily readable and easier to change or localize. I personally avoid placing long lines of text directly into the code of an application unless they are very static and don't need localization - internal exception message text, and the like.

当然,另一种选择是将字符串外部化到配置文件或设置文件中。这将使其更易于阅读,更易于更改或本地化。我个人避免将长行文本直接放入应用程序的代码中,除非它们非常静态并且不需要本地化 - 内部异常消息文本等。

回答by Tj Kellie

If you want to keep the code as minimal as you can and be able to read it easily I would still go with a @ literal string. Plus its faster if you source is long and..

如果您想尽可能减少代码并能够轻松阅读它,我仍然会使用 @ 文字字符串。此外,如果您的来源很长而且速度更快。

string verbatimLit = @" 
   __   __  
  /  `-'  \ 
 /_| N   |_\  Sometimes
   |  I  |    format in code
   |   N |    matters
   |_____|  
";

Then remove the newlines from the string in 1 line,

然后从 1 行的字符串中删除换行符,

verbatimLit.Replace(Environment.NewLine, " ");

回答by John Saunders

For SQL queries or other long strings that have their own syntax, I'll sometimes do something like this:

对于 SQL 查询或其他有自己语法的长字符串,我有时会这样做:

        private const string QUERY = @"
SELECT *
FROM Table1 AS T1
INNER JOIN Table2 AS T2 ON T1.ID = T2.T1ID
WHERE T1.VALUE = @P1
GROUP BY T2.OTHERVALUE
";

This leaves the formatting of the string intact.

这使字符串的格式保持不变。

回答by Johannes Rudolph

When finding yourself in question on how to do multiline strings, you might be better of using a Resources file.

当发现自己对如何处理多行字符串有疑问时,最好使用 Resources 文件。

回答by Alexei

Following Tj Kellieanswer, in C# 6.0 you can easily have one instruction to perform concatenation and embedding of various information through string interpolation and also not having newlines in spite of defining the string on multiple lines.

以下Tj Kellie答案,在 C# 6.0 中,您可以轻松地使用一条指令通过字符串插值来执行各种信息的连接和嵌入,并且尽管在多行上定义了字符串,但也没有换行符。

A complex example involving all these can look like the following:

涉及所有这些的复杂示例如下所示:

public int? BestTime { get; set; }
public int? WorstTime { get; set; }
public int? AvgTime { get; set; }
public int TimeoutReachedCount { get; set; }
public int AllRunCount { get; set; }

public string Str => $@"
   Ran {AllRunCount} times; 
   Reached timeout {TimeoutReachedCount} times; 
   Best time = {(BestTime.HasValue ? BestTime.ToString() : "N/A")}; 
   Worst time = {(WorstTime.HasValue ? WorstTime.ToString() : "N/A")}; 
   Average time = {(AvgTime.HasValue ? AvgTime.ToString() :"N/A")};"
       .Replace(Environment.NewLine, "");

Of course, extra care must be used to append blanks at the end of the lines to avoid words merging.

当然,必须格外小心地在行尾添加空格以避免单词合并。