C#基礎學習之委託

來源:互聯網
上載者:User

委託(delegate)

委託屬於參考型別,用於封裝方法(函數)的引用。它類似於C++中的函數指標,但有所不同,委託是完全物件導向的,是型別安全和可靠的;另外,C++指標僅指向成員函數,而委託同時封裝了對象執行個體和方法。

 

使用委託包含幾個步驟:委託聲明、委託執行個體化和委託調用

1、委託聲明

委託聲明用於定義一個從System.Delegate類派生的類,其格式為:

屬性集 修飾符 delegate 傳回值類型 標識符(形參列表);

 

其中,修飾符可為public、protected、internal、private和new

2、委託執行個體化

委託執行個體化用於建立委託執行個體化,與類執行個體建立的文法相同,委託執行個體可以封裝多個,

方法,該方法的集合稱為調用列表,委託使用“+”,“+=”,“-”,“-=”運算子向調用列表中增加或移除方法。

3、委託調用例子

     View Code

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

namespace Delegate
{
    delegate void TimeDelegate(string s);  //委託聲明
    //建立一個類
    public class MyTime
    {
        public static void HelloTime(string s)
        {
            Console.WriteLine("Hello {0}!The time is {1} now", s, DateTime.Now);
        }
        public static void GoodbyeTime(string s)
        {
            Console.WriteLine("Goodbye {0}!The time is {1} now", s, DateTime.Now);
        }
        public void SayHello(string s)
        {
            Console.WriteLine("{0}!The time is {1} now", s, DateTime.Now);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //委託執行個體化,建立委託執行個體a,並封裝靜態方法
            TimeDelegate a = new TimeDelegate(MyTime.HelloTime);
            Console.WriteLine("Invoking delegate a: ");
            //委託調用,相當於調用方法MyTime.HelloTime("A")
            a("A");

            TimeDelegate b = new TimeDelegate(MyTime.GoodbyeTime);
            Console.WriteLine("Invoking delegate b: ");
            b("B");

            //委託執行個體c封裝了兩個方法HelloTime和GoodbyeTime
            TimeDelegate c = a + b;
            Console.WriteLine("Invoking delegate c: ");
            c("C");

            c -= a;
            Console.WriteLine("Invoking delegate c: ");
            c("C");

            MyTime time = new MyTime();
            TimeDelegate d = new TimeDelegate(time.SayHello);
            Console.WriteLine("Invoking delegate d: ");
            d("D");

        }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.