C# delegate delegate statement simplifies evolution

1. Delegate basic statement form

Define a delegate type, instantiate the delegate type, assign a function to the delegate instance, and then call the delegate instance to realize the delegate.

namespace Vision
{
    delegate void dHelp();//定义委托

    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            dHelp h;//委托实例

            h = SaySometing;//实例赋值

            h();//委托调用

            void SaySometing()
            {
                MessageBox.Show("Hello");
            }

        }
    }
}

2. The role of entrustment

The delegate is used to store the behavior (that is, the method), and the behavior is determined by the caller.

namespace QLVision
{
    delegate void dHelp();//定义委托

    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            void Talk(dHelp help)//传参为委托
            {
                help();//方法内执行委托方法
            }

            void SayHello()
            {
                MessageBox.Show("Hello");
            }
            void SayBye()
            {
                MessageBox.Show("Bye");
            }

            Talk(SayHello);//方法调用
            Talk(SayBye);//方法调用

        }
    }
}

3. Classification of entrustment

It has nothing to do with the method name and method body, only classified by return type, parameter type, and number of parameters.

 4. Simplification of delegation

Generic delegate:

Action : Returns no value; Link: Action Delegate (System) | Microsoft Docs

Func : has a return value; link: Func<TResult> delegate (System) | Microsoft Docs

namespace QLVision
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            void Talk(Action help)//传参为委托
            {
                help();//执行委托方法
            }

            Talk(SayHello);//调用方法

            void SayHello()
            {
                MessageBox.Show("Hello");
            }
        }
    }
}

Use lambda expressions:

namespace QLVision
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            void Talk(Action help)//传参为委托
            {
                help();//执行委托方法
            }

            Talk(() => MessageBox.Show("Hello"));//Lamda表达式

        }
    }
}

Reference link: The reason why you don't use delegation is because you don't know enough about it.._哔哩哔哩_bilibili

Learn from each other and get rich together.

Guess you like

Origin blog.csdn.net/m0_62778855/article/details/125997511