C # study notes: commission

Bibliography: C # 6.0 study notes - from the first line of the first C # code to the project design (Author Zhoujia An) P92

Learning Objective: To understand the concept of trust

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

namespace Example3_13
{
    //定义一个委托
    public delegate void MyDelegate();
    class Program
    {
        static void Main(string[] args)
        {
            MyDelegate de = Method1;
            Test(de);
            //执行Test方法后重新调用委托
            de();
            Console.ReadKey();
        }

        //定义一个Test方法
        static void Test(MyDelegate d)
        {
            //调用委托
            if(d!= null)
            {
                d();
            }
            d = Method2;     //将委托改为与M2方法关联
                            //内部改变,不影响委托调用后的结果
        }

        //定义方法,以备委托调用
        static void Method1()
        {
            Console.WriteLine("调用方法1");
        }
        static void Method2()
        {
            Console.WriteLine("调用方法2");
        }
    }
}

Results are as follows:

Published 41 original articles · won praise 1 · views 878

Guess you like

Origin blog.csdn.net/qq_41708281/article/details/104243906