在我们的一个应用程序中,我遇到过这样的行:
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.WriteLine
的 fixed 调用,在此处传递 string.Empty
没有任何意义。
为了简单起见,您应该更喜欢 Console.WriteLine()
而不是 Console.WriteLine(string.Empty)
。
关于c# - Console.WriteLine() 与 Console.WriteLine(string.Empty),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38432513/