【问题标题】:C# turning console output on/offC# 打开/关闭控制台输出
【发布时间】:2017-01-24 22:36:15
【问题描述】:

我正在制作一个使用 SharpPcap 分析网络流量的 C# DLL。我想要实现的功能之一是可切换控制台输出。这个想法是在我的课堂上有一个方法

public void ConsoleOutputOn(bool outputOn)

如果需要控制台输出,则接收 true,否则接收 false。我不知道我将如何实现它。

我可以在 LUA 中编写

local dprint2 = function() end
function consoleOutput(outputOn)
  if (outputON == true) then
    dprint2 = function(...)
      print(...)
    end
  else
    dprint2 = function() end
  end
end

如果调用了 consoleOutput(true),则 dprint2 将变为 print,并且每次调用 dprint2 时,输入参数将被传递给 print 并在控制台输出上打印。如果调用了 consoleOutput(false),那么 dprint2 将是一个什么都不做的空函数。

我尝试在 C# 中做同样的事情,我的类将有私有变量“consoleOn”,而不是 print 我会调用

public void ConsoleOuptput(...) {
  if(outputOn) {
    Console.WriteLine(...);
  }
} 

这将检查“consoleOn”是否为真,如果是,则将参数发送到 Console.WriteLine()。

问题是 Console.WriteLine() 对所有类型的输入参数都重载了 19 次。有没有办法编写“如果 sonsoleOn 将所有参数传递给 Console.WriteLine()”。或者有没有更好的方法来制作可切换的控制台输出。

请记住,我正在制作 DLL。我不能完全关闭控制台。

【问题讨论】:

  • 如果您只需要控制从您自己的代码生成的输出,那么像ConsoleOutput 这样的包装方法为什么不够好?

标签: c# console console-application


【解决方案1】:

另一种选择是简单地将Console 包装为可切换类:

public class MyToggableConsole
{
    public bool On { get; }
    public void WriteLine(string message)
    {
        if (!On)
           return;

        Console.WriteLine(msg);
    }

    //Do same for all other `WriteLine` and `Write` overloads you need.
}

或者如果它非常本地化,比如说一种方法,你甚至可以考虑基于outputOn定义一个本地Action

var WriteToOutput = outputOn ? new Action<string>(s => Console.WriteLine(s) : new Action<string>(s => { } );

【讨论】:

  • 但这不会删除功能吗?新包装的控制台现在只能将字符串作为参数,而不是像 Console.WriteLine("{0}, {1}, {2}", value1, value2, value3); 这样的参数。是这样吗,那不是我需要的。更简单的 tat 解决方案只是创建一个方法来检查 outputOn 是否为真并传递字符串
  • @dantex47 因此我加入了评论;对您可能需要的所有其他重载执行相同的操作。此外,如果您使用 c# 6,使用字符串插值,您实际上并不需要更多。
【解决方案2】:

我最近非常成功地使用的一种方法是使用允许为空的记录器实例(可能只是TextWriter)。。现在,纯粹主义者可能会认为“空对象是一种反模式”,但它允许一些很棒的用法,例如:

log?.WriteLine($"Connection from '{from}' to '{to}', {data.Length} bytes to process...");

如果log 实例是null,则基本上是免费的,这要归功于评估短路的方式。当然,Console.OutTextWriter,所以如果你想启用控制台日志记录:

myApp.Log = Console.Out;

但同样,您可以登录到文件、网络套接字或其他任何内容 - 只需更改您分配给 myApp.Log 的内容即可。如果是null:日志就会停止。

【讨论】:

    猜你喜欢
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    相关资源
    最近更新 更多