C#打开/关闭控制台输出
我正在制作一个C#DLL,使用SharpPcap分析网络流量。其中一个我想实现的是可控制的输出。这个想法是有一个方法在我的课C#打开/关闭控制台输出
public void ConsoleOutputOn(bool outputOn)
如果控制台输出的希望接收真,假,如果它不是。我不知道我会如何实现这一点。
在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#中,我班将有私有变量“consoleOn”,而不是打印我会打电话
public void ConsoleOuptput(...) {
if(outputOn) {
Console.WriteLine(...);
}
}
,将检查是否“consoleOn”是真实的,如果它是,将参数发送到Console.WriteLine()。
问题是Console.WriteLine()对所有类型的输入参数重载了19次。如果sonsoleOn将所有参数传递给Console.WriteLine(),是否还有编码的方法?或者有更好的方法来制作可切换的控制台输出。
请记住我在做DLL。我不能完全转动控制台。我最近用得十分成功地与该
一种方法是使用记录器实例(可能只是TextWriter
)是被允许为空。现在,纯粹主义者可能会想“空对象是一个反模式”,但它允许一些真棒使用,例如:
log?.WriteLine($"Connection from '{from}' to '{to}', {data.Length} bytes to process...");
然后将其基本上是免费如果log
实例null
,感谢评估短路的方式。当然,Console.Out
是TextWriter
,所以如果你想启用控制台日志记录:
myApp.Log = Console.Out;
但同样可以登录到一个文件或网络套接字,或其他任何东西 - 只是通过改变你分配给什么myApp.Log
。如果是null
:记录只是停止。
另一种选择是简单地包装Console
用toggable类:
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 => { });
如果你只需要控制你自己的代码生成的输出,那么为什么像ConsoleOutput这样的包装方法不够好呢? – NicoE