委託、Lambda運算式、事件系列01,委託是什麼,委託的基本用法,委託的Method和Target屬性

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   使用   ar   sp   

委託是一個類。

namespace ConsoleApplication1
{
    internal delegate void MyDelegate(int val);
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

使用Reflector查看委託的IL代碼:

○ 委託的確是一個類
○ 委託的建構函式接收方法和類執行個體
○ 而且是多播委託,可以用+=為委託變數賦值
○ 委託內部使用Invoke方法觸發方法
○ BeginInvoke和EndInvoke方法用於多線程情境

 

接下來體驗委託如何使用,以及委託的Method和Target屬性分別代表什麼。

namespace ConsoleApplication1
{
    internal delegate void MyDelegate(int val);
    class Program
    {
        static void Main(string[] args)
        {
            //委託與靜態方法
            MyDelegate d = new MyDelegate(M1);
            d(10);
            Console.WriteLine(d.Method);
            if (d.Target == null)
            {
                Console.WriteLine("當前委託調用的是靜態方法,沒有類執行個體");
            }
            else
            {
                Console.WriteLine("當前委託調用的是執行個體方法,類執行個體為:" + d.Target);
            }
            Console.WriteLine("-------------------");
            
            //委託與執行個體方法
            Program p = new Program();
            d = p.M2;
            d.Invoke(10);
            Console.WriteLine(d.Method);
            if (d.Target == null)
            {
                Console.WriteLine("當前委託調用的是靜態方法,沒有類執行個體");
            }
            else
            {
                Console.WriteLine("當前委託調用的是執行個體方法,類執行個體為:" + d.Target);
            }
        }
        static void M1(int val)
        {
            Console.WriteLine("我是靜態方法,輸出" + val);
        }
        void M2(int val)
        {
            Console.WriteLine("我是執行個體方法,輸出" + val);
        }
    }
}

○ 委託建立:通過委託建構函式,new MyDelegate(M1);也可通過d = p.M2,這是一種"文法糖"寫法,其內部也調用了委託建構函式。
○ 委託與靜態方法:只要兩者參數列表和傳回型別一致,可把靜態方法傳給委託建構函式
○ 委託與執行個體方法:只要兩者參數列表和傳回型別一致,可把執行個體方法傳給委託建構函式
○ 委託調用:像d.Invoke(10),通過委託的執行個體方法Invoke調用;像d(10),這是一種"文法糖"寫法,其內部也調用了執行個體方法Invoke。
○ Target屬性:委託所表示執行個體方法所屬的類執行個體名稱,如果是靜態方法,Target為null
○ Method屬性:委託所表示的方法,可能是靜態方法,也有可能是執行個體方法

委託、Lambda運算式、事件系列01,委託是什麼,委託的基本用法,委託的Method和Target屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.