c# - Console.WriteLine() 与 Console.WriteLine(string.Empty)

标签 c#

在我们的一个应用程序中,我遇到过这样的行:

Console.WriteLine(string.Empty);

我检查了如果我只写它是否有任何不同:

Console.WriteLine();

但输出是相同的(如预期的那样)。

这个例子中的“最佳实践”是什么?是否存在需要传递空 string 而不是不传递任何参数的情况?

最佳答案

WriteLine()是这样实现的:

public virtual void WriteLine() {
    Write(CoreNewLine);
}

WriteLine(string)然而是这样实现的:

public virtual void WriteLine(String value) {
    if (value==null) {
        WriteLine();
    }
    else {
        // We'd ideally like WriteLine to be atomic, in that one call
        // to WriteLine equals one call to the OS (ie, so writing to 
        // console while simultaneously calling printf will guarantee we
        // write out a string and new line chars, without any interference).
        // Additionally, we need to call ToCharArray on Strings anyways,
        // so allocating a char[] here isn't any worse than what we were
        // doing anyways.  We do reduce the number of calls to the 
        // backing store this way, potentially.
        int vLen = value.Length;
        int nlLen = CoreNewLine.Length;
        char[] chars = new char[vLen+nlLen];
        value.CopyTo(0, chars, 0, vLen);
        // CoreNewLine will almost always be 2 chars, and possibly 1.
        if (nlLen == 2) {
            chars[vLen] = CoreNewLine[0];
            chars[vLen+1] = CoreNewLine[1];
        }
        else if (nlLen == 1)
            chars[vLen] = CoreNewLine[0];
        else
            Buffer.InternalBlockCopy(CoreNewLine, 0, chars, vLen * 2, nlLen * 2);
        Write(chars, 0, vLen + nlLen);
    }
}

如果您使用 null 字符串调用它,那么您将获得与不带参数的 WriteLine() 相同的结果(加上一个额外的方法调用)。然而,传递非空字符串时的逻辑有点复杂。

对于 string.Empty,这将分配一个长度为 2 的新字符数组,并将换行符复制到该数组中。

这通常并不昂贵,但如果您不想打印任何东西,它仍然有些多余。尤其是对于 Console.WriteLinefixed 调用,在此处传递 string.Empty 没有任何意义。

为了简单起见,您应该更喜欢 Console.WriteLine() 而不是 Console.WriteLine(string.Empty)

关于c# - Console.WriteLine() 与 Console.WriteLine(string.Empty),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38432513/

相关文章:

C# 和 Kinect v2 : Get RGB values that fit to depth-pixel

C#龙书(词法分析)如何处理字面量

c# - 如何在 Visual Studio 中配置内部版本号以启用 dll 比较

C# : overriding Method with optional parameters & named parameters : Unexpected Result

c# - 如何通过向 Nhibernate 3.3.3.4001 中的 Session.Delete(...) 发送查询来删除对象

c# - nHibernate 存储过程调用

c# - 我可以在后面的代码中读取 css 类运行时的内容吗?

c# - 如何在没有代码隐藏文件的情况下移动无边界 wpf 窗口

C# - GroupPrincipal.GetMembers(true) - 哪个组?

c# - 复古适配新语言功能 C#(或任何其他语言)