简体   繁体   English

禁止引用包中的 Console.Write

[英]Suppress Console.Write in referenced package

In one project, I reference a NuGet package which outputs text to the Console when some of its methods are called.在一个项目中,我引用了一个 NuGet 包,该包在调用其某些方法时将文本输出到控制台。

I would prefer it didn't, as I am writing things to the Console in my own code.我宁愿它没有,因为我正在用我自己的代码向控制台写东西。

Is there a way to suppress the Console writing happening in that package, but still be able to write to Console myself?有没有办法抑制该包中发生的控制台写入,但仍然可以自己写入控制台?

You can use Console.SetOut to set the default output to any other TextWriter - but still use the original Console.Out .可以使用Console.SetOut将默认输出设置为任何其他TextWriter - 但仍使用原始Console.Out Here's a demo of that:这是一个演示:

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.");
    }
}

That does work - but it's pretty annoying.这确实有效 - 但它很烦人。 I would personally ask the author of the original package to modify the package if possible - it's pretty odd for a library to write to the console by default.如果可能的话,我个人会要求原始包的作者修改包 - 默认情况下,库写入控制台非常奇怪。 It should at least allow you to specify which TextWriter to write to.它至少应该允许您指定要写入的TextWriter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM