简体   繁体   English

在C#中,在多条源代码行之间散布单行字符串文字的最佳方法是什么?

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

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 did want 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't want newlines. 我想知道,当您希望使用换行符时,是否还有一样干净的东西。

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). 在这里,我在等号后的行上开始字符串,以使它们全部对齐,并且还要确保空格出现在行的末尾(同样,出于对齐目的)。

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, " ");

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. 我个人避免将长行文本直接放入应用程序的代码中,除非它们非常静态并且不需要本地化(内部异常消息文本等)。

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. 这使字符串的格式保持不变。

Following Tj Kellie answer, 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. 当然,必须格外小心在行末添加空白,以避免单词合并。

当发现有关如何处理多行字符串的问题时,最好使用Resources文件。

You could use multiple consts and then combine them into one big string: 您可以使用多个const,然后将它们组合成一个大字符串:

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. 如果需要,可以在多个文件或类型中定义子字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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