"\n"和环境。换行符

这两者之间的区别是什么(如果有的话)?

384049 次浏览

这取决于平台。在Windows上,它实际上是“\r\n”。

从MSDN:

包含"\r\n"的字符串 非unix平台,或者字符串 对于Unix平台,包含“\n”

文档

包含"\r\n"的字符串 非unix平台,或者字符串 对于Unix平台,包含“\n”

环境。NewLine在Windows上运行时会给出“\r\n”。如果你正在为基于Unix的环境生成字符串,你不需要“\r”。

Environment.NewLine将返回运行代码的相应平台的换行符

当你在linux的莫诺框架上部署你的代码时,你会发现这非常有用

正如其他人所提到的,Environment.NewLine返回一个特定于平台的字符串,用于开始新行,它应该是:

  • "\r\n" (\u000D\u000A)用于Windows
  • "\n" (\u000A)用于Unix
  • "\r" (\u000D) for Mac(如果存在这样的实现)

注意,当写入控制台时,环境。NewLine不是必须的。如果需要,控制台流将把"\n"转换为适当的新行序列。

当您试图显示以“\r\n”分隔的多行消息时,可能会遇到麻烦。

以标准的方式做事,并使用环境总是一个很好的实践。换行符

从源代码中精确实现Environment.NewLine:

.NET 4.6.1中的实现:

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
**        platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
get {
Contract.Ensures(Contract.Result<String>() != null);
return "\r\n";
}
}

source


在。net Core中的实现:

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the
**        given platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
get {
Contract.Ensures(Contract.Result() != null);
#if !PLATFORM_UNIX
return "\r\n";
#else
return "\n";
#endif // !PLATFORM_UNIX
}
}

(在System.Private.CoreLib中)

public static string NewLine => "\r\n";

(在System.Runtime.Extensions中)