學習筆記-委託

   //委託的作用就是把方法封裝成一個委託類型的變量
    //這個類型承載了一個或者多個方法
//委託時候可以連加的,委託是可以被執行的。就想調用方法一樣。
  delegate void DL(int i);
    class Program
    {     
        static void Main(string[] args)
        {
            Program p = new Program();
            DL dl = new DL(ff);
            DL d2 = new DL(FFF);
            //委託的匿名使用
            DL d4 = delegate(int i) { Console.WriteLine("wu"); Console.WriteLine(i); };
            // DL d5 = new DL({Console.WriteLine("wu"); Console.WriteLine(i);});//錯誤的使用匿名方法
            DL dl3 = dl + d2 + d4 ;
            dl3(2);
        }
        static void ff(int i)
        {
            Console.WriteLine("ff");
        }
        static void FFF(int i)
        {
            Console.WriteLine("FFF");
        }
    }
            //在使用 連加時候 無論是委託還是 方法名 都必須與定義的委託保持一致。
            //委託連加的實質就是調用了Delegate.Combine()方法
-----------------------------------------------------------------
    //class Phone
    //{
    //}
    //class Mobile : Phone
    //{
    //}
    //delegate Phone PhoneDele(Mobile m);
    //像定義方法簽名一樣定義委託
    //class Program
    //{
    //    static void Main(string[] args)
    //    {
    //        Program pro = new Program();
    //        PhoneDele pd1 = pro.GetPhone;
    //        PhoneDele pd2 = pro.GetMobile;--協變
    //        pd2(new Mobile ());
    //    }
    //    public Phone GetPhone(Mobile m)
    //    {
    //        return null;
    //    }
    //    public Mobile GetMobile(Phone f)
    //    {
    //        return null;
    //    }
    //    public Phone GetPhone(Phone f)
    //    {
    //        return null;
    //    }
    //    public Mobile GetMobile(Mobile m)
    //    {
    //        return null;
    //    }
    //}   
    //class Phone
    //{ }
    //class Mobile : Phone
    //{ }
    //delegate void PhoneDele(Mobile pho);
    //class Program
    //{
    //    static void Main(string[] args)
    //    {
    //        Program pro = new Program();
    //        PhoneDele pd1 = pro.SetPhone;//委託類型的逆變
    //        PhoneDele pd2 = pro.SetMobile;
    //        pd1(new Mobile());
    //    }
    //    public void SetPhone(Phone pho)
    //    { }
    //    public void SetMobile(Mobile mob)
    //    { }
    //
    1: 方法不必與委託簽名完全匹配 ,但是方法的簽名必須具有繼承關係,無論是 返回值還是參數類表
    2: 什麼是協變是 是委託的返回值與方法的返回值 如果前者返回值類型是後者返回值類型的父類就可以 否則不行,協變只發生在返回值有繼承關係的委託賦值過程(即把方法賦給委託變量)
    3: 什麼是逆變是 把一個方法給委託變量,委託的參數類型一定是方法中參數的的子類。
          逆變只發生在委託參數和方法參數有繼承關係的委託賦值過程。
      那麼在調用委託的時候,傳給委託的參數是被調用的方法的參數的子類,一個子類賦給父類對象是符合c#語法規範的
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章