Unity C# Basics Review 27 - Delegate Example (P448)

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

namespace ConsoleApp1
{
    class Cook
    {
        public static String Step1()
        {
            Console.WriteLine("放油");
            return null;
        }
        public static String Step2()
        {
            Console.WriteLine("放葱");
            return null;
        }
        public static String Step3()
        {
            Console.WriteLine("放菜");
            return null;
        }
        public static String Step4()
        {
            Console.WriteLine("放调料");
            return null;
        }
        public static String Step5()
        {
            return "糖醋里脊";
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    delegate String Cooking();
    class Program
    {
        static void Main(string[] args)
        {

            Cooking cook = Cook.Step1;
            cook += Cook.Step2;
            cook += Cook.Step3;
            cook += Cook.Step4;
            cook += Cook.Step5;

            cook -= Cook.Step1;
            String result = cook();
            Console.WriteLine(result);

        }
    }
}

 

The last return value is sweet and sour pork. If cook+=Cook.Step5 is adjusted forward, null will be printed.

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

namespace ConsoleApp1
{
    delegate String Cooking();
    class Program
    {
        static void Main(string[] args)
        {

            Cooking cook = Cook.Step1;
            
            cook += Cook.Step2;
            cook += Cook.Step3;
            cook += Cook.Step5;
            cook += Cook.Step4;
           
            String result = cook();
            Console.WriteLine(result);

        }
    }
}

 If the delegated process has a return value, you will always get the return value of the last method.

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/125471596