在引用包中抑制 Console.Write
Suppress Console.Write in referenced package
在一个项目中,我引用了一个 NuGet 包,当它的某些方法被调用时,它会将文本输出到控制台。
我希望它没有,因为我正在用自己的代码向控制台写入内容。
有没有办法抑制在那个包中发生的控制台写入,但仍然能够自己写入控制台?
您可以使用Console.SetOut
将默认输出设置为任何其他TextWriter
- 但仍然使用原始Console.Out
。这是一个演示:
using System;
using System.IO;
class Test
{
static void Main()
{
var originalOut = Console.Out;
Console.SetOut(TextWriter.Null);
LibraryMethod();
originalOut.WriteLine("This should still go to the console.");
}
static void LibraryMethod()
{
Console.WriteLine("Imagine this were in the referenced package.");
Console.WriteLine("This isn't going anywhere. It's being discarded.");
}
}
这确实有效 - 但它很烦人。如果可能的话,我个人会要求原始包的作者修改包——库默认写入控制台是很奇怪的。它至少应该允许您指定要写入的 TextWriter
。
在一个项目中,我引用了一个 NuGet 包,当它的某些方法被调用时,它会将文本输出到控制台。
我希望它没有,因为我正在用自己的代码向控制台写入内容。
有没有办法抑制在那个包中发生的控制台写入,但仍然能够自己写入控制台?
您可以使用Console.SetOut
将默认输出设置为任何其他TextWriter
- 但仍然使用原始Console.Out
。这是一个演示:
using System;
using System.IO;
class Test
{
static void Main()
{
var originalOut = Console.Out;
Console.SetOut(TextWriter.Null);
LibraryMethod();
originalOut.WriteLine("This should still go to the console.");
}
static void LibraryMethod()
{
Console.WriteLine("Imagine this were in the referenced package.");
Console.WriteLine("This isn't going anywhere. It's being discarded.");
}
}
这确实有效 - 但它很烦人。如果可能的话,我个人会要求原始包的作者修改包——库默认写入控制台是很奇怪的。它至少应该允许您指定要写入的 TextWriter
。