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.使用委托實現異步執行

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM