如何禁用Console.WriteLine等输出
又想到一个靠谱点的方法,不过调用会有些麻烦,参考下面的代码。
class ConsoleOut : TextWriter { private ConsoleOut(TextWriter output) { _out = output; } private TextWriter _out; public override Encoding Encoding { get { return _out.Encoding; } } public override void Write(char value) { if (__outputEnabled) _out.Write(value); } private static ConsoleOut __instance; public static void Install() { if (__instance == null) { __instance = new ConsoleOut(Console.Out); Console.SetOut(__instance); } } private static bool __outputEnabled; public static bool OutputEnabled { get { return __outputEnabled; } set { __outputEnabled = value; } } }
示例:
// 调用示范 ConsoleOut.Install(); Console.WriteLine("这行不会输出"); ConsoleOut.OutputEnabled = true; Console.WriteLine("这行可以输出"); ConsoleOut.OutputEnabled = false; Console.WriteLine("这行也不会输出");