在 C# 源代码中打破长字符串的最佳方法

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

Best way to break long strings in C# source code

c#string

提问by Alexander Prokofyev

I am wondering what is the "best practice" to break long strings in C# source code. Is this string

我想知道在 C# 源代码中打破长字符串的“最佳实践”是什么。这是字符串吗

"string1"+
"string2"+
"string3"

concatenated during compiling or in run time?

在编译期间或在运行时连接?

采纳答案by Jon Skeet

It's done at compile time. That's exactly equivalent to "string1string2string3".

它是在编译时完成的。这完全等同于“string1string2string3”。

Suppose you have:

假设你有:

string x = "string1string2string3"
string y = "string1" + "string2" + "string3"

The compiler will perform appropriate interning such that x and y refer to the same objects.

编译器将执行适当的实习,以便 x 和 y 引用相同的对象。

EDIT: There's a lot of talk about StringBuilderin the answers and comments. Many developers seem to believe that string concatenation should alwaysbe done with StringBuilder. That's an overgeneralisation - it's worth understanding why StringBuilderis good in some situations, and not in others.

编辑:StringBuilder答案和评论中有很多讨论。许多开发人员似乎认为字符串连接应该始终使用StringBuilder. 这是一种过度概括 - 值得理解为什么StringBuilder在某些情况下是好的,而在其他情况下则不是

回答by Maxam

The concatenation is done at compile time, so there is no runtime overhead.

连接在编译时完成,因此没有运行时开销。

回答by Damien

Can't you use a StringBuilder?

你不能用StringBuilder吗?

回答by James Newton-King

Your example will be concatenated at compile time. All inline strings and const string variables are concatenated at compile time.

您的示例将在编译时连接。所有内联字符串和 const 字符串变量在编译时连接在一起。

Something to keep in mind is that including any readonly strings will delay concatting to runtime. string.Empty and Environment.NewLine are both readonly string variables.

需要记住的是,包含任何只读字符串将延迟连接到运行时。string.Empty 和 Environment.NewLine 都是只读字符串变量。

回答by Tamir

it really depends on what you need. Generally, if you need to concat strings, the best performance in runtime will be achieved by using StringBuilder. If you're referring in source code something like var str = "String1"+"String2" it will be converter into string str = "String1String2" on compilation. In this case you have no concatenation overhead

这真的取决于你需要什么。一般情况下,如果需要对字符串进行concat,运行时的性能最好使用StringBuilder。如果您在源代码中引用类似 var str = "String1"+"String2" 的内容,它将在编译时转换为字符串 str = "String1String2"。在这种情况下,您没有连接开销

回答by Rune Grimstad

If the whitespace isn't important then you can use the @ escape character to write multi-line strings in your code. This is useful if you have a query in your code for example:

如果空格不重要,那么您可以使用 @ 转义字符在代码中编写多行字符串。如果您的代码中有查询,这很有用,例如:

string query = @"SELECT whatever
FROM tableName
WHERE column = 1";

This will give you a string with line breaks and tabs, but for a query that doesn't matter.

这将为您提供一个带有换行符和制表符的字符串,但对于无关紧要的查询。

回答by Sani Singh Huttunen

StringBuilder is a good way to go if you have many (more than about four) strings to concatenate. It's faster.

如果您有很多(超过大约四个)字符串要连接,则 StringBuilder 是一个很好的方法。它更快。

Using String.Concat in you example above is done at compile time. Since they are literal strings they are optimized by the compiler.

在上面的示例中使用 String.Concat 是在编译时完成的。由于它们是文字字符串,因此它们由编译器优化。

If you however use variables:

但是,如果您使用变量:

string a = "string1";
string b = "string2";
string c = a + b;

This is done at runtime.

这是在运行时完成的。

回答by naspinski

StringBuilder will be your fastest approach if you are using any amount of strings.

如果您使用任意数量的字符串,StringBuilder 将是您最快的方法。

http://dotnetperls.com/Content/StringBuilder-1.aspx

http://dotnetperls.com/Content/StringBuilder-1.aspx

If you are just doing a few string (5 or less is a good rule) the speed will not matter of what kind of concatenation you are using.

如果你只是在做几个字符串(5 个或更少是一个很好的规则),速度将与你使用的连接类型无关。

回答by naspinski

There′s any way to do it. My favorete uses a string′s method′s from C#. Sample One:

有什么办法可以做到。我最喜欢使用 C# 中的字符串方法。示例一:

string s=string.Format("{0} {1} {0}","Hello","By"); result is s="Hello By Hello";

string s=string.Format("{0} {1} {0}","Hello","By"); 结果是 s="Hello By Hello";

回答by B12Toaster

How about the following extension method(which is inspired by common-tags oneLinemethod)...

下面的扩展方法怎么样(受 common-tags oneLine方法的启发)...

using System;
using System.Text.RegularExpressions;
using static System.Text.RegularExpressions.RegexOptions;

namespace My.Name.Space
{
    public static class StringHelper
    {
        public static string AsOneLine(this string text, string separator = " ")
        {
            return new Regex(@"(?:\n(?:\s*))+").Replace(text, separator).Trim();
        }
    }
}

...in combination with the verbatim string literalused as such:

...结合使用的逐字字符串文字

var mySingleLineText = @"
    If we wish to count lines of code, we should not regard them
    as 'lines produced' but as 'lines spent'.
".AsOneLine();

Note that spaces "inside" the string are kept intact, for example:

请注意,字符串“内部”的空格保持不变,例如:

// foo      bar hello        world.
var mySingleLineText = @"
    foo      bar
    hello        world.
".AsOneLine();

If you don't want newlines to be substituted with spaces, then pass ""as argument to the extension method:

如果您不想用空格替换换行符,则将""作为参数传递给扩展方法:

// foobar
var mySingleLineText = @"
    foo
    bar
".AsOneLine("");

Please note:This form of string concatenation is conducted at run time due to the helper-method involved (in contrast to concatenation via the +operator occurring at compile time, as also stated in the accepted answer). So if performance is an issue, go with the +. If you are dealing with long phrases and readability and "ease of use" is the focus, then the approach suggested above may be worth considering.

请注意:由于所涉及的辅助方法,这种形式的字符串连接是在运行时进行的(与通过+在编译时发生的运算符进行连接相反,如已接受的答案中所述)。因此,如果性能是一个问题,请使用+. 如果您正在处理长短语和可读性并且“易用性”是重点,那么上面建议的方法可能值得考虑。