在一个项目中,我引用了一个 NuGet 包,当它的某些方法被调用时,它会将文本输出到控制台。
我希望它没有,因为我正在用自己的代码向控制台写入内容。
有没有办法抑制该包中发生的控制台写入,但我自己仍然能够写入控制台?
最佳答案
您可以使用 Console.SetOut
将默认输出设置为任何其他 TextWriter
- 但仍然使用原始的 Console。出
。这是一个演示:
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
。
关于c# - 抑制 Console.Write 在引用包中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59002914/