【发布时间】:2010-11-04 04:26:54
【问题描述】:
两者之间有什么区别(如果有的话)(对于 .Net)?
【问题讨论】:
标签: c# .net cross-platform
两者之间有什么区别(如果有的话)(对于 .Net)?
【问题讨论】:
标签: c# .net cross-platform
源码中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
}
}
source(在System.Private.CoreLib)
public static string NewLine => "\r\n";
source(在System.Runtime.Extensions)
【讨论】:
Environment.NewLine 将返回运行代码的相应平台的换行符
当您在Mono 框架上的 linux 中部署代码时,您会发现这非常有用
【讨论】:
当您尝试显示以“\r\n”分隔的多行消息时,您可能会遇到麻烦。
以标准方式做事并使用 Environment.NewLine 总是一个好习惯
【讨论】:
取决于平台。在 Windows 上,它实际上是 "\r\n"。
来自 MSDN:
包含“\r\n”的字符串 非 Unix 平台,或字符串 对于 Unix 平台,包含“\n”。
【讨论】:
Environment.NewLine 是 \r\n 但 \n 也称为“新行”。他们为什么不直接将后者称为“换行”并消除混淆呢?他们也可以使用\l。
正如其他人所提到的,Environment.NewLine 返回一个特定于平台的字符串,用于开始新的一行,它应该是:
"\r\n" (\u000D\u000A) 适用于 Windows"\n" (\u000A) 用于 Unix"\r" (\u000D) 适用于 Mac(如果存在此类实现)请注意,在写入控制台时,Environment.NewLine 并不是绝对必要的。如有必要,控制台流会将"\n" 转换为适当的换行符序列。
【讨论】:
\n
Environment.NewLine 在 Windows 上运行时将给出“\r\n”。如果要为基于 Unix 的环境生成字符串,则不需要 "\r"。
【讨论】:
来自docs ...
包含“\r\n”的字符串 非 Unix 平台,或字符串 对于 Unix 平台,包含“\n”。
【讨论】: