SoFunction
Updated on 2025-03-07

C# delegation treats methods as parameters (example explanation)

Static method proxy:

Copy the codeThe code is as follows:

public delegate void DoGreeting(string name);

class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
//The method name is passed as a parameter to the delegate type call
MarkGreeting("Zhang San", GreetingEnglish);
MarkGreeting("Li Si", GreetingChinese);
        }

        /// <summary>
/// Delegate (Agent method)
        /// </summary>
        /// <param name="name"></param>
        /// <param name="markGreeting"></param>
        private static void MarkGreeting(string name, DoGreeting markGreeting)
        {
            markGreeting(name);
        }

        /// <summary>
/// Say hello in English
        /// </summary>
        /// <param name="name"></param>
        private static void GreetingEnglish(string name)
        {
           (name+"hello!");
        }

        /// <summary>
/// Say hello in Chinese
        /// </summary>
        /// <param name="name"></param>
        private static void GreetingChinese(string name)
        {
(name+"Hello!");
        }
    }


Instance method proxy:
Copy the codeThe code is as follows:

 public delegate void DoGreeting(string name);

    public class Greeting
    {
        /// <summary>
/// Delegate (Agent method)
        /// </summary>
        /// <param name="name"></param>
        /// <param name="markGreeting"></param>
        public void MarkGreeting(string name, DoGreeting markGreeting)
        {
            markGreeting(name);
        }

        /// <summary>
/// Say hello in English
        /// </summary>
        /// <param name="name"></param>
        public  void GreetingEnglish(string name)
        {
            (name + "hello!");
        }

        /// <summary>
/// Say hello in Chinese
        /// </summary>
        /// <param name="name"></param>
        public void GreetingChinese(string name)
        {
(name + "Hello!");
        }
    }

    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Greeting greetingObj = new Greeting();

("Zhang San", );
("Li Si", );

        }