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 reflector and 'decompiled' the code for the Console.WriteLine
method and found this:
我发现这个小方法使用intellisense,然后打开.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以这种方式实现呢?它完全只是一条捷径还是有另一个原因?
2 个解决方案
#1
46
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是一个静态对象,可以作为参数传递给任何采用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),或者基于某些运行时条件的任何其他内容
#2
4
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#编程语言”。
#1
46
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是一个静态对象,可以作为参数传递给任何采用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),或者基于某些运行时条件的任何其他内容
#2
4
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#编程语言”。