lundi 8 mars 2021

In C# Is there a smarter way to overload a set of methods with different names with a number of signatures?

I am building a logging class and it formats the message differently based on the method name. I want to be able to use it in a similar way to how Console.WriteLine() works. Overloading works just fine, but I want to do this with a set of different methods, the name being the determining factor on the formatting option.

I am looking to see if there is a 'smarter' way to do this other then writing every overloaded method of every version of the same method over and over. That just feels so, bug prone.

Some examples of how I want to use it:

        Logger Log = new Logger();
        Log.Prod ("Main Log Window");
        Log.Warn ("This is a Warning Message");
        Log.Error ("This is an Error Message");
        Log.Network ("This is a Network Message");
        Log.Verbose ("This is for Verbose Message Reporting");
        Log.Processing ("Analaysis Related Message");

For what I mean how to use Console.WriteLine, I mean in ways like this:

        String Name = "Sam";
        String Day = "Monday";
        int hour = 11;
        int minute = 30;
        Console.WriteLine ("Hello World");
        Console.WriteLine ("Hello {0}", Name);
        Console.WriteLine ("{0}, the time is {1}:{2}", Name, hour, minute);

So, what I would end up with is more like this:

        Logger Log = new Logger();
        Log.Prod ("Staring Application");
        Log.Warn ("Data {0} looks Corrupt",data);
        Log.Error ("Error: {0}", message);
        Log.Network ("User {0} logged in from {1}", user, network);
        Log.Verbose ("This is for Verbose Message Reporting");
        Log.Processing ("Analaysis Related Message");

Now, I know I can code each and every overloaded method for each of those versions of the same routine, (remember, each will format the message a little differently), and I could put some kind of 'code' on it, like:

        Log.Write (Log.Error ,"Error: {0}", message);

... and Log.Error be some kind of enum or what ever, but this is nasty.

What I'd like to do is bake this all down to a case statement that would handle the formatting and then feed that into the output. Most of the code I need to write is all this overloading relaying that's 99% repeat of the same exact thing. There's got to be a smarter way.

I've seen a few things in other languages that might do this, but I am looking for a C# (.Net Framework 4.8) way of doing this if possible. What would be the 'cleanest' and 'smarter' way of doing it besides writing it all out?

I've looked at overloading, overriding, templates, interfaces, etc. But so far, it all looks as if it would wind up being the same outcome or worse.

Aucun commentaire:

Enregistrer un commentaire