c# Escape Seq \n 不工作

c# Escape Seq \n not working

我正在尝试在 WinForm app:VS2015 .net 4.5

中插入这样的新行
  class Program
{
    private static List<ZONE> zones;

    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("line1" + Environment.NewLine);
        sb.Append("line2");

    }

}

sb.ToString 不包含 "line1" 和 "line2" 之间的换行符 不知道为什么。

\n的含义取决于您使用的平台。如果你在windows,实际上是\r\n

但更好的是,请使用 Environment.NewLine 属性。

使用 StringBuilder.AppendLine() 它会自动附加当前的 Environment.NewLine 值。

 class Program
 {
    private static List<ZONE> zones;

    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("line1");
        sb.AppendLine("line2");
        Console.WriteLine(sb.ToString());

    }
}

sb.ToString() 上的断点内有 THIS,如您所见,断点就在那里。

所以它会输出你所期望的,或者至少应该。这没有考虑本地化问题。

你可以试试这个:

  StringBuilder sb = new StringBuilder();

  sb.Append("line1");
  sb.AppendLine();
  sb.Append("line2");

  String result = sb.ToString();

或者更好的是:

  String result = String.Join(Environment.NewLine, "line1", "line2");