"\n"和Environment.NewLine之间的区别

Pre*_*k K 192 .net c# cross-platform

两者之间有什么区别(如果有的话)(相对于.Net)?

ant*_*ony 193

取决于平台.在Windows上它实际上是"\ r \n".

来自MSDN:

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

  • @Jack你可能正在写一个将在Unix平台上打开的文件.或者发送将由unix平台接收的包中的文本.几个月后,.net将在Unix平台上运行.它已经开始了 (10认同)
  • .NET运行到.NET的哪个UNIX平台放入其doc?(我的意思是,Mono的一部分.) (5认同)

alo*_*ica 146

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

资源


.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
    }
}
Run Code Online (Sandbox Code Playgroud)

来源(中System.Private.CoreLib)

public static string NewLine => "\r\n";
Run Code Online (Sandbox Code Playgroud)

来源(中System.Runtime.Extensions)

  • 还有其他人期待这么简单的代码吗?:d (16认同)
  • 是的:)由于某种原因,我期待.NET实现是一个非常复杂的功能 (8认同)

P D*_*ddy 69

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

  • "\r\n" (\ u000D\u000A)适用于Windows
  • "\n" (\ u000A)用于Unix
  • "\r" (\ u000D)for Mac(如果存在此类实现)

请注意,写入控制台时,不一定要使用Environment.NewLine."\n"如有必要,控制台流将转换为适当的新行序列.

  • 只是一个注释,那将是旧的mac; new(OSX)mac使用`\n` (22认同)
  • @Dykam,是的,但是在我的HP48gx上运行起来确实很慢 (2认同)
  • @Blieque 只是说 2009 年可能是真的,但事实并非如此。我没查。 (2认同)

Ron*_*ony 22

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

当您在Mono框架上的Linux中部署代码时,您会发现这非常有用


JP *_*oto 8

来自文档 ......

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


Yah*_*hya 5

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

以标准方式做事并使用 Environment.NewLine 始终是一个好习惯