简体   繁体   中英

How can I cleanly pass a parameter to a delegate?

Below is MSDN code from delegate section.

The code is working as excepted but I would like to know how do I input message into this small logging component.

Which one is the correct way to input an error message? Should I use: Logger.WriteMessage or Logger.LogMessage Although both is printing a message to the screen

Logger.WriteMessage(error_msg1);

or

Logger.LogMessage(error_msg2);
using System;

namespace DelegateTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string error_msg1 = "101 : Error Disk";
            string error_msg2 = "104 : Error Retriving";

            Logger.WriteMessage += LoggingMethods.LogToConsole;


            Logger.WriteMessage(error_msg1);
            Logger.LogMessage(error_msg2);


            Console.Read();
        }
    }

    public static class Logger
    {
        public static Action<string> WriteMessage;

        public static void LogMessage(string msg)
        {
            WriteMessage(msg);
        }
    }

    public static class LoggingMethods
    {
        public static void LogToConsole(string message)
        {
            Console.Error.WriteLine(message);
        }
    }
}

Use LogMessage. It is part of the Logger's intended API and may add extra functionality (adding a time-stamp). It should also guard against WriteMessage being null.

Logger.WriteMessage is the 'plug-in' point. You shouldn't use it to write anything and you shouldn't assume it is not null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM