天天看點

C#的委托

1,delegate是什麼?

msdn定義:委托是一種引用方法的類型.一旦為委托配置設定了方法,委托将與該方法具有完全相同的行為.委托方法的使用可以像其他任何方法一樣,具有參數和傳回值.

其聲明如下:

C#的委托

public   delegate   void  TestDelegate( string  message);

C#的委托

 多路廣播委托:可以使用 + 運算符将它們配置設定給一個要成為多路廣播委托的委托執行個體。組合的委托可調用組成它的那兩個委托。隻有相同類型的委托才可以組合。

- 運算符可用來從組合的委托移除元件委托。

2,delegate的特點?

delegate類似于c++的函數指針,但它是類型安全的;

delegate是引用類型,使用前必須new下(static除外);

委托允許将方法作為參數進行傳遞;

委托可以連結在一起;例如,可以對一個事件調用多個方法;

方法不需要與委托簽名精确比對.參見協變和逆變(協變允許将帶有派生傳回類型的方法用作委托,逆變允許将帶有派生參數的方法用作委托。);

C#2.0引入了匿名方法的概念,此類方法允許将代碼作為參數傳遞,以代替單獨定義的方法.

3,delegate怎麼用? 

三步:聲明declare  

public delegate void Del<T>(T item);
public void Notify(int i) { }      

           執行個體化instantiation

Del<int> d1 = new Del<int>(Notify);      
在 C# 2.0 中,還可以使用下面的簡化文法來聲明委托:      

           調用invocation

4,為什麼用delegate?

還不是很清楚,按我的了解就是寫出面向對象高品質的代碼,設計子產品中觀察者子產品就以delegate/event實作

5,何時使用委托而不使用接口?(msdn)

委托和接口都允許類設計器分離類型聲明和實作。給定的接口可由任何類或結構繼承和實作;可以為任何類中的方法建立委托,前提是該方法符合委托的方法簽名。接口引用或委托可由不了解實作該接口或委托方法的類的對象使用。既然存在這些相似性,那麼類設計器何時應使用委托,何時又該使用接口呢?

在以下情況中使用委托:

  • 當使用事件設計模式時。
  • 當封裝靜态方法可取時。
  • 當調用方不需要通路實作該方法的對象中的其他屬性、方法或接口時。
  • 需要友善的組合。
  • 當類可能需要該方法的多個實作時。

在以下情況中使用接口:

  • 當存在一組可能被調用的相關方法時。
  • 當類隻需要方法的單個實作時。
  • 當使用接口的類想要将該接口強制轉換為其他接口或類類型時。
  • 當正在實作的方法連結到類的類型或辨別時:例如比較方法。

6,舉例說明:

C#的委托

// copy by msdn,changed by me

C#的委托

using  System;

C#的委托

//  Declare delegate -- defines required signature:

C#的委托

delegate   void  SampleDelegate( string  message);

C#的委托
C#的委托

class  MainClass

C#的委托
C#的委托

... {

C#的委托

    // Regular method that matches signature:

C#的委托

    static void SampleDelegateMethod(string message)

C#的委托
C#的委托

    ...{

C#的委托

        Console.WriteLine(message);

C#的委托

    }

C#的委托

    //non-static method that mathches signature;

C#的委托

    public void Sample(string message)

C#的委托
C#的委托

    ...{

C#的委托

        Console.WriteLine(message);

C#的委托

    }

C#的委托

    static void Main()

C#的委托
C#的委托

    ...{

C#的委托

        // Instantiate delegate with named method:

C#的委托

        SampleDelegate d1 = SampleDelegateMethod;

C#的委托

        // Instantiate delegate with anonymous method:

C#的委托

        SampleDelegate d2 = delegate(string message)

C#的委托
C#的委托

        ...{

C#的委托

            Console.WriteLine(message);

C#的委托

        };

C#的委托

        // Create an instance of the delegate with static method;

C#的委托

        SampleDelegate d3=new SampleDelegate(SampleDelegateMethod);

C#的委托

        //Create an instance of the delegate with new instance;

C#的委托

        MainClass myclass = new MainClass();

C#的委托

        SampleDelegate d4 = new SampleDelegate(myclass.Sample); 

C#的委托

        // Invoke delegate d1:

C#的委托

        d1("Hello");

C#的委托

        // Invoke delegate d2:

C#的委托

        d2(" World");

C#的委托

        d3("static");

C#的委托

        d4("non-static");

C#的委托

    }

C#的委托

}