C # enable / disable console

I am making a C # DLL that analyzes network traffic using SharpPcap. One of the tags I want to implement is togglable console output. The idea is to have a method in my class

public void ConsoleOutputOn(bool outputOn)

which gets true if console output is desired, and false if it is not. I do not know how to implement this.

In LUA, I could write

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

If consoleOutput (true) is called, dprint2 will become a print, and each time dprint2 is called, input arguments will be passed for printing and printing to the console output. If consoleOutput (false) was called, than dprint2 would be an empty function that did nothing.

I tried to do the same in C #, my class will have a private variable consoleOn, and instead of printing I would call

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

, "consoleOn", , Console.WriteLine().

, Console.WriteLine() 19 . " sonsoleOn Console.WriteLine()". toggleable .

, DLL. .

+4
2

, , - (, 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: .

+3

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.
}

, , , Action outputOn:

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

Source: https://habr.com/ru/post/1654829/


All Articles