C# 转换控制台输出 on/off

C# turning console output on/off

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

中有一个方法
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 将变为打印,每次调用 dprint2 时,输入参数将传递给打印并打印在控制台输出上。如果调用了 consoleOutput(false),那么 dprint2 将是什么都不做的空函数。

我尝试在 C# 中做同样的事情,我的 class 会有私有变量 "consoleOn",我会调用

而不是打印
public void ConsoleOuptput(...) {
  if(outputOn) {
    Console.WriteLine(...);
  }
} 

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

问题是 Console.WriteLine() 对于各种输入参数重载了 19 次。甚至有编码 "if sonsoleOn pass all arguments to Console.WriteLine()" 的方法吗?或者有没有更好的方法来制作可切换的控制台输出。

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

我最近非常成功地使用了一种方法,即使用允许 为 null 的记录器实例(可能只是 TextWriter)。现在,纯粹主义者可能会想 "null objects are an anti-pattern",但它允许一些很棒的用法,例如:

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

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

myApp.Log = Console.Out;

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

另一种选择是简单地用可切换的 class 包装 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 => { } );