简体   繁体   中英

What's the correct way to use delegate?

During one of my lab sessions I was given a problem related to delegates which I solved as belows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateApp
{
    delegate void GreeterDelegate();

    class Program
    {
        static void GreetGoodMorning()
        {
            if (DateTime.Now.ToString().EndsWith("AM"))
                Console.WriteLine("Good Morning!");
        }

        static void GreetGoodEvening()
        {
            if (DateTime.Now.ToString().EndsWith("PM"))
                Console.WriteLine("Good Evening!");
        }

        static void Main(string[] args)
        {
            GreeterDelegate Greeters = new GreeterDelegate(GreetGoodMorning);
            Greeters += GreetGoodEvening;

            Greeters();

            Console.ReadLine();
        }
    }
}

What I did was that I used the conditions to check time inside the methods. But one of the Lab Faculty suggested me to do this either:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateApp
{
    delegate void GreeterDelegate();

    class Program
    {
        static void GreetGoodMorning()
        {
            Console.WriteLine("Good Morning!");
        }

        static void GreetGoodEvening()
        {
            Console.WriteLine("Good Evening!");
        }

        static void Main(string[] args)
        {
            GreeterDelegate Greeters;

            if (DateTime.Now.ToString().EndsWith("AM"))
                Greeters = new GreeterDelegate(GreetGoodMorning);
            else
                Greeters = new GreeterDelegate(GreetGoodEvening);

            Greeters();

            Console.ReadLine();
        }
    }
}

He suggested to move the conditions out from the methods into the Main() method. The End result is the same but I am still confused about which way is the better way to do it especially considering the use of delegates in large programs, whether the conditional check should be moved into the methods or should be kept outside.

The last sample is better because you have no redundant checks wich method to use + less calls. This will result in better performance because your check will happen at run-time.

This isn't really a question of delegates, but coding practice.

In your code you're calling both delegates, but only one displays text in the console.

In the suggested code only one delegate is called.

The second implementation is more efficient and the one that you should use. From a programming point of view the intent of the code is also clearer.

Whenever you're going to perform an action it's better to decide which action you want to perform first and then do that, rather than place the checks in each action.

If you fancy beans for dinner you don't get every can out of the cupboard and then decide if you want beans and whether that can has beans in it or not. You check each can to see if it has beans in it and only get that one down.

Neither of them is good code. These are just constructed samples to show the syntax and usage of delegates. In this sample you wouldn't need a delegate at all, because it is just a normal call to a function.

Delegates are useful under the following conditions:

  • Methods determinded dynamically at run time (method A, B or C is called)
  • Callback methods (enable to specify a method which is called by some other method)
  • Multicast operations (method A, B and C are called by some code X. X does not have any information about A, B or C)

The two samples don't have the same meaning. I would prefer the first version because it does what it says. GreetGoodMorning checks whether it's morning or not and doesn't do anything when it isn't. I would rewrite the 2nd version into the following:

 static void Greet() 
 { 
    if (DateTime.Now.ToString().EndsWith("PM")) 
        Console.WriteLine("Good Evening!"); 
    else
        Console.WriteLine("Good Morning!"); 
 } 

Nobody should write any code just to use a delegate.

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