C# 委托delegate的基本用法

委托:就是一个方法的类型,下面3个调用情况来详细熟悉一下:

1.调用组合委托

    //委托:就是一个方法的类型
    public delegate int TestDelegateStr();
    public delegate string TestDelegateInt(int a);

    public  class 委托
    {
        //实例化委托:需要一个方法来实例化
        public static TestDelegateStr tdstr1;
        public static TestDelegateInt tdint  ;

        public static void main()
        {
            tdstr1 = testfunctionStr;
            tdstr1 = tdstr1 + testfunction;
            int result = tdstr1();  //调用组合委托
            Console.WriteLine("result" + result.ToString());

            tdint = testfunctionInt;
            tdint(1);
            Console.ReadKey();
        }

        public static int testfunction()
        {
            Console.WriteLine("111");
            return 1;
        }
        public static int testfunctionStr()
        {
            Console.WriteLine("222");
            return 2;
        }
        public static string testfunctionInt(int a)
        {
            Console.WriteLine("testfunction3");
            return " test";
        }
    }

2.委托之前的赋值:

        public delegate int CalculateDelegate(int a, int b);
        public void main()
        {
            CalculateDelegate cal;
            //让用户输入两个参数x和y
            //如果x>y,输出x-y
            //如果x<=y,输出x+y
            int x = 5; int y = 3;
            if (x > y)
            {
                cal = Minus;
            }
            else
            {
                cal = add;
            }
            int result= cal(x, y);
            Console.WriteLine(result.ToString());
        }

        public int add(int a, int b)
        {
            return a + b;
        }
        public int Minus(int a, int b)
        {
            return a - b;
        }
    }

3.委托delegate和Lambda之前的切换写法:

    public class 委托3
    {
        public delegate int CalculateDelegate(int a, int b);
        public delegate int CalculateDelegate2(int a);
        public void main()
        {
            CalculateDelegate cal;
            CalculateDelegate2 cal2;
            //让用户输入两个参数x和y
            //如果x>y,输出x-y
            //如果x<=y,输出x+y
            int x = 3; int y = 5;
            if (x > y)
            {
                cal = delegate (int a, int b) { return a - b; };  //匿名方法
            }
            else
            {
                //cal = delegate (int a, int b) { return a + b; };
                cal = (int a, int b) => { return a + b; };   //Lambda和上句等价
            }
            //简化1:如果Lambda方法体中只有一个返回值,那么大括号和return可以省略
            cal = (int a, int b) => a + b;

            //简化2:在Lambda的参数列表中,参数类型可以省略
            cal = (a, b) => a + b;

            //简化3:如果在Lambda参数列表中只有一个参数,那么参数的括号可以省略
            cal2 = a => a * a;



            int result= cal(x, y);
            Console.WriteLine(result.ToString());
        }
        
    }

4.使用委托实现异步执行

原文地址:https://www.cnblogs.com/parkerchen/p/12853726.html