Delegate 類別

定義

表示委派,這個資料結構指的是靜態方法,或類別執行個體與該類別的執行個體方法。

public ref class Delegate abstract
public ref class Delegate abstract : ICloneable, System::Runtime::Serialization::ISerializable
public abstract class Delegate
public abstract class Delegate : ICloneable, System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Serializable]
public abstract class Delegate : ICloneable, System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Delegate : ICloneable, System.Runtime.Serialization.ISerializable
type Delegate = class
type Delegate = class
    interface ICloneable
    interface ISerializable
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)>]
[<System.Serializable>]
type Delegate = class
    interface ICloneable
    interface ISerializable
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)>]
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Delegate = class
    interface ICloneable
    interface ISerializable
Public MustInherit Class Delegate
Public MustInherit Class Delegate
Implements ICloneable, ISerializable
繼承
Delegate
衍生
屬性
實作

範例

下列範例顯示如何定義名為的委派 myMethodDelegate 。 這個委派的實例是針對實例方法和嵌套類別的靜態方法所建立 mySampleClass 。 實例方法的委派需要實例 mySampleClassmySampleClass實例會儲存在名為的變數中 mySC

using namespace System;
delegate String^ myMethodDelegate( // Declares a delegate for a method that takes in an int and returns a String.
int myInt );

// Defines some methods to which the delegate can point.
ref class mySampleClass
{
public:

   // Defines an instance method.
   String^ myStringMethod( int myInt )
   {
      if ( myInt > 0 )
            return ("positive");

      if ( myInt < 0 )
            return ("negative");

      return ("zero");
   }


   // Defines a static method.
   static String^ mySignMethod( int myInt )
   {
      if ( myInt > 0 )
            return ("+");

      if ( myInt < 0 )
            return ("-");

      return ("");
   }

};

int main()
{
   
   // Creates one delegate for each method. For the instance method, an 
   // instance (mySC) must be supplied. For the static method, only the
   // method name is needed.
   mySampleClass^ mySC = gcnew mySampleClass;
   myMethodDelegate^ myD1 = gcnew myMethodDelegate( mySC, &mySampleClass::myStringMethod );
   myMethodDelegate^ myD2 = gcnew myMethodDelegate( mySampleClass::mySignMethod );
   
   // Invokes the delegates.
   Console::WriteLine( "{0} is {1}; use the sign \"{2}\".", 5, myD1( 5 ), myD2( 5 ) );
   Console::WriteLine( "{0} is {1}; use the sign \"{2}\".",  -3, myD1(  -3 ), myD2(  -3 ) );
   Console::WriteLine( "{0} is {1}; use the sign \"{2}\".", 0, myD1( 0 ), myD2( 0 ) );
}

/*
This code produces the following output:

5 is positive; use the sign "+".
-3 is negative; use the sign "-".
0 is zero; use the sign "".
*/
using System;
public class SamplesDelegate  {

   // Declares a delegate for a method that takes in an int and returns a string.
   public delegate string myMethodDelegate( int myInt );

   // Defines some methods to which the delegate can point.
   public class mySampleClass  {

      // Defines an instance method.
      public string myStringMethod ( int myInt )  {
         if ( myInt > 0 )
            return( "positive" );
         if ( myInt < 0 )
            return( "negative" );
         return ( "zero" );
      }

      // Defines a static method.
      public static string mySignMethod ( int myInt )  {
         if ( myInt > 0 )
            return( "+" );
         if ( myInt < 0 )
            return( "-" );
         return ( "" );
      }
   }

   public static void Main()  {

      // Creates one delegate for each method. For the instance method, an
      // instance (mySC) must be supplied. For the static method, use the
      // class name.
      mySampleClass mySC = new mySampleClass();
      myMethodDelegate myD1 = new myMethodDelegate( mySC.myStringMethod );
      myMethodDelegate myD2 = new myMethodDelegate( mySampleClass.mySignMethod );

      // Invokes the delegates.
      Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", 5, myD1( 5 ), myD2( 5 ) );
      Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", -3, myD1( -3 ), myD2( -3 ) );
      Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", 0, myD1( 0 ), myD2( 0 ) );
   }
}


/*
This code produces the following output:

5 is positive; use the sign "+".
-3 is negative; use the sign "-".
0 is zero; use the sign "".
*/
Public Class SamplesDelegate

   ' Declares a delegate for a method that takes in an int and returns a String.
   Delegate Function myMethodDelegate(myInt As Integer) As [String]

   ' Defines some methods to which the delegate can point.
   Public Class mySampleClass

      ' Defines an instance method.
      Public Function myStringMethod(myInt As Integer) As [String]
         If myInt > 0 Then
            Return "positive"
         End If
         If myInt < 0 Then
            Return "negative"
         End If
         Return "zero"
      End Function 'myStringMethod

      ' Defines a static method.
      Public Shared Function mySignMethod(myInt As Integer) As [String]
         If myInt > 0 Then
            Return "+"
         End If
         If myInt < 0 Then
            Return "-"
         End If
         Return ""
      End Function 'mySignMethod
   End Class

   Public Shared Sub Main()

      ' Creates one delegate for each method. For the instance method, an
      ' instance (mySC) must be supplied. For the Shared method, the
      ' method name is qualified by the class name.
      Dim mySC As New mySampleClass()
      Dim myD1 As New myMethodDelegate(AddressOf mySC.myStringMethod)
      Dim myD2 As New myMethodDelegate(AddressOf mySampleClass.mySignMethod)

      ' Invokes the delegates.
      Console.WriteLine("{0} is {1}; use the sign ""{2}"".", 5, myD1(5), myD2(5))
      Console.WriteLine("{0} is {1}; use the sign ""{2}"".", - 3, myD1(- 3), myD2(- 3))
      Console.WriteLine("{0} is {1}; use the sign ""{2}"".", 0, myD1(0), myD2(0))

   End Sub

End Class


'This code produces the following output:
' 
'5 is positive; use the sign "+".
'-3 is negative; use the sign "-".
'0 is zero; use the sign "".

備註

Delegate類別是委派類型的基類。 不過,只有系統和編譯器可以明確地衍生自 Delegate 類別或 MulticastDelegate 類別。 也不允許從委派型別衍生新的型別。 此 Delegate 類別不會被視為委派型別,而是用來衍生委派類型的類別。

大部分的語言 delegate 都能採用關鍵字,而這些語言的編譯器可以從類別衍生, MulticastDelegate 因此使用者應該使用 delegate 語言所提供的關鍵字。

注意

Common language runtime 會 Invoke 為每個委派型別提供一個方法,其簽章與委派相同。 您不需要明確地從 c #、Visual Basic 或 Visual C++ 呼叫這個方法,因為編譯器會自動呼叫這個方法。 Invoke當您想要尋找委派型別的簽章時,方法會在反映中相當有用。

Common language runtime 會提供每個具有和方法的委派型別 BeginInvoke EndInvoke ,以啟用委派的非同步調用。 如需這些方法的詳細資訊,請參閱 以非同步方式呼叫同步方法

委派類型的宣告會建立合約,以指定一或多個方法的簽章。 委派是委派類型的實例,其具有下列參考:

  • 類型的實例方法,以及可指派給該類型的目標物件。

  • 類型的實例方法,具有在型式 this 參數清單中公開的隱藏參數。 委派稱為開放實例委派。

  • 靜態方法。

  • 靜態方法和目標物件,可指派給方法的第一個參數。 委派會被視為要在其第一個引數上關閉。

如需委派系結的詳細資訊,請參閱方法多載 CreateDelegate(Type, Object, MethodInfo, Boolean)

注意

在 .NET Framework 1.0 和1.1 版中,只有當方法的簽章完全符合委派類型所指定的簽章時,委派才能表示方法。 因此,只支援上述清單中的第一個和第三個專案符號,而第一個專案符號需要完全相符的型別。

當委派表示在其第一個引數上關閉的實例方法時 (最常見的案例) ,委派會儲存對方法進入點的參考,以及物件的參考,稱為「目標」(type),此類型可指派給定義方法的型別。 當委派代表開啟的實例方法時,它會儲存對方法進入點的參考。 委派簽章必須 this 在其型式參數清單中包含 hidden 參數,在此情況下,委派並沒有目標物件的參考,而且必須在叫用委派時提供目標物件。

當委派表示靜態方法時,委派會儲存對方法進入點的參考。 當委派代表其第一個引數封閉的靜態方法時,委派會儲存方法進入點的參考,以及可指派給方法第一個引數之類型的目標物件參考。 當叫用委派時,靜態方法的第一個引數會收到目標物件。 第一個引數必須是參考型別。

委派的調用清單是一組已排序的委派,其中清單的每個元素都只會叫用委派所表示的其中一個方法。 調用清單可包含重複的方法。 在叫用期間,會依它們出現在調用清單中的順序來叫用方法。 委派嘗試叫用其調用清單中的每個方法;重複專案會在每次出現在調用清單中時叫用一次。 委派是不可變的;一旦建立之後,就不會變更委派的調用清單。

委派稱為多播或可組合,因為委派可以叫用一或多個方法,並可用於組合作業。

合併作業(例如 CombineRemove )不會改變現有的委派。 相反地,這類作業會傳回新的委派,其中包含作業的結果、未變更的委派或 nullnull當作業的結果是未參考至少一個方法的委派時,結合作業會傳回。 當要求的作業沒有作用時,結合作業會傳回未變更的委派。

注意

Managed 語言使用 CombineRemove 方法來執行委派作業。 範例包含 AddHandler RemoveHandler Visual Basic 中的和語句,以及 c # 中委派類型的 + = 和-= 運算子。

從 .NET Framework 4 開始,泛型委派類型可以有 variant 型別參數。 您可以使用逆變型別參數做為委派的參數類型,而且可以使用協變數型別參數做為傳回型別。 如果泛型委派型別引數是具有繼承關聯性的參考型別(如共 變數和反變數所述),則這項功能可讓您從相同的泛型型別定義建立的泛型委派型別為指派相容。

注意

因為變異數不一定可組合,所以與指派相容的泛型委派。 若要加以組合,類型必須完全相符。 例如,假設名為的類別 Derived 衍生自名為的類別 Base 。 您 Action<Base> Action(Of Base) 可以將 Visual Basic) 中 (類型的委派指派給類型的變數 Action<Derived> ,但無法合併這兩個委派,因為類型不完全相符。

如果叫用的方法擲回例外狀況,此方法就會停止執行,並將例外狀況傳回給委派的呼叫端,而不會叫用調用清單中的其餘方法。 攔截呼叫端中的例外狀況並不會改變此行為。

當委派叫用的方法簽章包含傳回值時,委派會傳回檔用清單中最後一個元素的傳回值。 當簽章包含以傳址方式傳遞的參數時,參數的最後值會是順序中每個方法的結果,並更新參數的值。

在 C 中,最接近的委派等於函式指標。 委派可以表示靜態方法或實例方法。 當委派代表實例方法時,委派不僅會儲存對方法進入點的參考,也會儲存類別實例的參考。 和函式指標不同的是,委派是物件導向且型別安全。

建構函式

Delegate(Object, String)

初始化委派,這個委派會在指定的類別執行個體上叫用指定的執行個體方法。

Delegate(Type, String)

初始化委派,這個委派會從指定的類別叫用指定的靜態方法。

屬性

Method

取得委派所表示的方法。

Target

取得目前的委派在其中叫用執行個體方法的類別執行個體。

方法

Clone()

建立委派的淺層複本 (Shallow Copy)。

Combine(Delegate, Delegate)

串連兩個委派的引動過程清單。

Combine(Delegate[])

串連委派陣列的引動過程清單。

CombineImpl(Delegate)

串連指定的多點傳送 (可結合的) 委派和目前多點傳送 (可結合的) 委派的引動過程清單。

CreateDelegate(Type, MethodInfo)

建立指定類型的委派來表示指定的靜態方法。

CreateDelegate(Type, MethodInfo, Boolean)

建立指定之類型的委派,用來表示指定之靜態方法,並包含在繫結失敗時發生的指定之行為。

CreateDelegate(Type, Object, MethodInfo)

建立指定之類型的委派,其表示指定之靜態或執行個體方法,並有指定第一個引數。

CreateDelegate(Type, Object, MethodInfo, Boolean)

建立指定之類型的委派,其表示指定之靜態或執行個體方法,並有指定第一個引數以及繫結失敗時所發生的行為。

CreateDelegate(Type, Object, String)

建立指定類型的委派,這個委派表示要在指定的類別執行個體上叫用的指定執行個體方法。

CreateDelegate(Type, Object, String, Boolean)

建立指定類型的委派,這個委派表示要在指定的類別執行個體上,使用指定的大小寫區分來叫用的指定執行個體方法。

CreateDelegate(Type, Object, String, Boolean, Boolean)

建立指定之類型的委派,其表示要在指定的類別執行個體上叫用的指定執行個體方法,且會指定區分大小寫的方式以及在繫結失敗時要發生的行為。

CreateDelegate(Type, Type, String)

建立指定類型的委派,這個委派表示指定類別的指定靜態方法。

CreateDelegate(Type, Type, String, Boolean)

建立指定之類型的委派,其表示指定之類別的指定靜態方法,且指定區分大小寫的方式。

CreateDelegate(Type, Type, String, Boolean, Boolean)

建立指定之類型的委派,其表示指定之類別的指定靜態方法,且會指定區分大小寫的方式以及在繫結失敗時要發生的行為。

DynamicInvoke(Object[])

動態叫用 (晚期繫結) 目前委派所表示的方法。

DynamicInvokeImpl(Object[])

動態叫用 (晚期繫結) 目前委派所表示的方法。

Equals(Object)

判斷指定的物件和目前的委派是否具有相同類型,並共用相同的目標、方法和引動過程清單。

GetHashCode()

傳回委派的雜湊碼。

GetInvocationList()

傳回委派的引動過程清單。

GetMethodImpl()

取得目前委派所表示的靜態方法。

GetObjectData(SerializationInfo, StreamingContext)

不支援。

GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
Remove(Delegate, Delegate)

從另一個委派的引動過程清單,移除委派的引動過程清單上最後一個項目。

RemoveAll(Delegate, Delegate)

從另一個委派的引動過程清單,移除委派的引動過程清單上所有的項目。

RemoveImpl(Delegate)

從另一個委派的引動過程清單移除委派的引動過程清單。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

運算子

Equality(Delegate, Delegate)

判斷指定的委派是否相等。

Inequality(Delegate, Delegate)

判斷指定的委派是否不相等。

擴充方法

GetMethodInfo(Delegate)

取得表示特定委派所代表之方法的物件。

適用於

另請參閱