C# 为什么 Console.Out.WriteLine 存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1149131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does Console.Out.WriteLine exist?
提问by Kredns
Actually the question should be why does Console.WriteLine
exist just to be a wrapper for Console.Out.WriteLine
实际上问题应该是为什么Console.WriteLine
存在只是为了包装Console.Out.WriteLine
I found this little method using intellisense, then opened .NET reflectorand 'decompiled' the code for the Console.WriteLine
method and found this:
我使用智能感知找到了这个小方法,然后打开.NET 反射器并“反编译”了该Console.WriteLine
方法的代码,发现了这个:
public static void WriteLine(string value)
{
Out.WriteLine(value);
}
So why is WriteLine
implemented this way? Is it totally just a shortcut or is there another reason?
那么为什么要这样WriteLine
实现呢?这完全只是一条捷径还是有其他原因?
采纳答案by Sam Harwell
Console.WriteLine
is a static method. Console.Out
is a static object that can get passed as a parameter to any method that takes a TextWriter
, and that method could call the non-static member method WriteLine
.
Console.WriteLine
是一个静态方法。Console.Out
是一个静态对象,可以作为参数传递给任何采用 a 的TextWriter
方法,并且该方法可以调用非静态成员方法WriteLine
。
An example where this would be useful is some sort of customizable logging routines, where you might want to send the output to stdout
(Console.Out
), stderr
(Console.Error
) or nowhere (System.IO.TextWriter.Null
), or anything else based on some runtime condition.
一个有用的示例是某种可自定义的日志记录例程,您可能希望将输出发送到stdout
( Console.Out
)、stderr
( Console.Error
) 或无处 ( System.IO.TextWriter.Null
),或基于某些运行时条件的任何其他内容。
回答by Abhilash NK
Brad Abrams(The founding member of both CLR and .NET framework at Microsoft) says the following.
Brad Abrams(微软 CLR 和 .NET 框架的创始成员)说如下。
Console.WriteLine() is simply a shortcut for Console.Out.WriteLine. Console was overloaded by WriteLine propery to make that much easier to write.
Console.WriteLine() 只是 Console.Out.WriteLine 的快捷方式。 控制台由 WriteLine 属性重载,以使其更容易编写。
Source: Book "The C# Programming Language by Anders Hejlsberg".
资料来源:“Anders Hejlsberg 的 C# 编程语言”一书。