在我们的一个应用程序中,我遇到过这样的一些行:
Console.WriteLine(string.Empty);
Run Code Online (Sandbox Code Playgroud)
如果我写的话,我检查了它是否有任何区别:
Console.WriteLine();
Run Code Online (Sandbox Code Playgroud)
但输出是相同的(如预期的那样).
这个例子中的"最佳实践"是什么?是否有必要传递空string而不是传递任何参数的情况?
WriteLine() 像这样实现:
public virtual void WriteLine() {
Write(CoreNewLine);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果用null字符串调用它,那么你得到的结果与WriteLine()没有参数的结果相同(加上一个额外的方法调用).但是,传递非空字符串时的逻辑有点复杂.
为此,string.Empty将分配一个长度为2的新字符数组,并将新行字符复制到该数组.
这通常不贵,但如果你不想打印任何东西,仍然有点多余.特别是对于固定电话Console.WriteLine来说,通过它没有任何意义string.Empty.
你应该更喜欢Console.WriteLine()过Console.WriteLine(string.Empty),如果单独为简单起见.