首页 文章

“\ n”和Environment.NewLine之间的区别

提问于
浏览
184

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

7 回答

  • 3

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

    来自MSDN:

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

  • 137

    从源代码中精确实现 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
        }
    }
    

    source(在 System.Private.CoreLib

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

    source(in System.Runtime.Extensions

  • 4

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

    • "\r\n" (\ u000D \ u000A)for Windows

    • "\n" (\ u000A)for Unix

    • "\r" (\ u000D)for Mac(如果存在此类实现)

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

  • 22

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

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

  • 67

    来自docs ......

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

  • 181

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

    以标准方式执行操作始终是一种好习惯,并使用Environment.NewLine

  • 8

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

相关问题