English 中文(简体)
创建多线护卫的最佳辛金
原标题:Best syntax to create multi-line string
  • 时间:2009-10-02 07:43:52
  •  标签:

在C#中创造多线通道的最佳途径是什么?

我知道以下方法:

Using StringBuilder

var result = new StringBuilder().AppendLine("one").AppenLine("two").ToString()

看起来太好。

Using @

      var result = @"one
two"

看上去,格式模糊不清。

Do you know better ways?

最佳回答

为此:

var result = string.Join(Environment.NewLine, new string[]{ 
    "one",
    "two" 
});

It s a bit painful and possibly an overkill, but it gives the possibility to preserve the lines separation in your code.
To improve things a little, you could use an helper method:

static string MultiLine(params string[] args) {
    return string.Join(Environment.NewLine, args);
}

static void Main(string[] args) {
    var result = MultiLine( 
        "one",
        "two" 
    );
}
问题回答

这一点是什么?

var result = "one
two";

如果你对专门处理事项的项目终止表示怀疑,请使用<编码>Format:

var result = String.Format("one{0}two", Environment.NewLine);

(Well,“幻灯”是正确的字眼:在处理文本档案时,在处理遗留软件时,往往需要或甚至需要专门处理的事项。)

“最佳”是一个非常开放的终点。

是:

  • Performance of the code
  • Speed the coder can write it
  • Ability for another coder to understand it easily
  • Ability for another coder to modify it easily

所有这一切都对“最佳”做事方式有很大不同。

我这样说,它取决于你们的需要。

但为了简化,我要谈谈:

var s = new StringBuilder();
s.Append("one");
s.Append("two");
s.ToString();

但既然我们不知道你们需要什么。 很难给人以更好的背后。

You should not define large strings in your source code. You should define it in an external text file:

string s = File.OpenText("myfile.txt").ReadToEnd();

what @codymanix 说,你可将长的多线插在资源档案中。 由于“档案”文本将列入你的DL/EXE号文件,因此某些部署情况可能比较容易。

Sometimes you need more than one line. I use Environment.NewLine but I placed it in a method to multiply it. :)

    private string newLines(int multiplier)
    {
        StringBuilder newlines = new StringBuilder();
        for (int i = 0; i < multiplier; i++)
            newlines.Append(Environment.NewLine);
        return newlines.ToString();
    }

Ehm, how to:

string s = 
  "abc
" + 
  "def
" ;




相关问题
热门标签