C#_委託_一個(組)或多個函數的封裝

C#_委託_一個(組)或多個函數的封裝



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

namespace 委託練習
{
    class Program
    {
        static void Main(string[] args)
        {
            /*委託練習1*/
            MyDele dele1 = new MyDele(M1);//引用的類型
                                          //dele1這個變數引用著一個MyDele類型的實體
                                          //這個實體裡面包覆著M1的方法

            Student stu = new Student();

            dele1 += stu.SayHello;
            dele1 += (new Student()).SayHello;
            //dele1 += M1;//委託除了可以包覆一個(組)函數,也可包覆若干個函數
            //一次調用可以調用好幾個函數


            //dele1.Invoke();//寫法1
            //利用我們的dele1所引用的MyDele類型調用委託實體間接調用其方法
            dele1();//寫法2


            /*委託練習2*/
            MyDele2 dele2 = new MyDele2(Add);

            int res = dele2(100, 200);
            Console.WriteLine(res);


            Console.ReadKey();
        }

        static void M1()
        {
            Console.WriteLine("M1 is called!!");
        }


        //靜態method
        static int Add(int x , int y)
        {
            return x + y;
        }

    }

    class Student {
        public void SayHello()
        {
            Console.WriteLine("Hello , Im a Student!");
        }
    }
    delegate void MyDele();//委託宣告,返回值類型是void


    delegate int MyDele2(int a, int b);



}






http://formatmysourcecode.blogspot.tw/










留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題