两者之间有什么不同 (关于.Net方面)?
根据操作系统平台而定。在Windows上实际上是 "\r\n"。
来自MSDN:
对于非Unix平台,它包含 "\r\n" 的字符串;对于Unix平台,它包含 "\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";
}
}
.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
中)
正如其他人提到的,Environment.NewLine
返回一个平台特定的字符串以开始新行,这应该是:
"\r\n"
(\u000D\u000A)适用于Windows"\n"
(\u000A)适用于Unix"\r"
(\u000D)适用于Mac(如果有此类实现)请注意,在写入控制台时,Environment.NewLine
并不是必须的。如果需要,控制台流将把"\n"
转换为适当的换行序列。
\n
。 - BlueRaja - Danny Pflughoeft当您尝试显示使用"\r\n"分隔的多行消息时,可能会遇到麻烦。
按照标准方式进行操作并使用Environment.NewLine始终是一个好习惯。
在Windows上运行Environment.NewLine会得到"\r\n"。如果您正在为基于Unix的环境生成字符串,则不需要"\r"。
Environment.NewLine
是\r\n
,但\n
也被称为“新行”。为什么他们不直接用更为常见的名称“换行符”来称呼后者,以消除混淆呢?他们本可以使用\l
。 - rory.ap