Delegate 類別

定義

表示委派,它是參考到靜態方法或該類別的類別執行個體和執行個體方法 (Instance Method) 的資料結構。Represents a delegate, which is a data structure that refers to a static method or to a class instance and an instance method of that class.

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

範例

下列範例顯示如何定義名為myMethodDelegate的委派。The following example shows how to define a delegate named myMethodDelegate. 這個委派的實例是針對實例方法和嵌套mySampleClass類別的靜態方法所建立。Instances of this delegate are created for an instance method and a static method of the nested mySampleClass class. 實例方法的委派需要的實例mySampleClassThe delegate for the instance method requires an instance of mySampleClass. 實例會儲存在名為mySC的變數中。 mySampleClassThe mySampleClass instance is saved in a variable named 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類別是委派類型的基類。The Delegate class is the base class for delegate types. 不過,只有系統和編譯器可以明確衍生自Delegate類別或MulticastDelegate類別。However, only the system and compilers can derive explicitly from the Delegate class or from the MulticastDelegate class. 也不允許從委派型別衍生新的型別。It is also not permissible to derive a new type from a delegate type. Delegate類別不會視為委派類型,它是用來衍生委派類型的類別。The Delegate class is not considered a delegate type; it is a class used to derive delegate types.

大部分語言都會實delegate作為關鍵字,而這些語言的編譯器可以衍生MulticastDelegate自類別,因此,使用者應該使用該語言所delegate提供的關鍵字。Most languages implement a delegate keyword, and compilers for those languages are able to derive from the MulticastDelegate class; therefore, users should use the delegate keyword provided by the language.

注意

通用語言執行時間會針對Invoke每個委派類型提供一個方法,其簽章與委派相同。The common language runtime provides an Invoke method for each delegate type, with the same signature as the delegate. 您不需要明確地從C#、Visual Basic 或視覺效果C++呼叫這個方法,因為編譯器會自動呼叫它。You do not have to call this method explicitly from C#, Visual Basic, or Visual C++, because the compilers call it automatically. Invoke您想要尋找委派類型的簽章時,方法在反映中很有用。The Invoke method is useful in reflection when you want to find the signature of the delegate type.

通用語言執行時間會提供具有BeginInvokeEndInvoke方法的每個委派類型,以啟用委派的非同步調用。The common language runtime provides each delegate type with BeginInvoke and EndInvoke methods, to enable asynchronous invocation of the delegate. 如需這些方法的詳細資訊,請參閱以非同步方式呼叫同步方法For more information about these methods, see Calling Synchronous Methods Asynchronously.

委派類型的宣告會建立合約,以指定一或多個方法的簽章。The declaration of a delegate type establishes a contract that specifies the signature of one or more methods. 委派是委派類型的實例,其中包含下列各項的參考:A delegate is an instance of a delegate type that has references to:

  • 類型的實例方法,以及可指派給該類型的目標物件。An instance method of a type and a target object assignable to that type.

  • 類型的實例方法,其中的 hidden this參數會公開在型式參數清單中。An instance method of a type, with the hidden this parameter exposed in the formal parameter list. 委派稱為開放式實例委派。The delegate is said to be an open instance delegate.

  • 靜態方法。A static method.

  • 可指派給方法之第一個參數的靜態方法和目標物件。A static method and a target object assignable to the first parameter of the method. 委派會被視為要在其第一個引數上關閉。The delegate is said to be closed over its first argument.

如需委派系結的詳細資訊, CreateDelegate(Type, Object, MethodInfo, Boolean)請參閱方法多載。For more information on delegate binding, see the CreateDelegate(Type, Object, MethodInfo, Boolean) method overload.

注意

在 .NET Framework 版本1.0 和1.1 中,只有在方法的簽章完全符合委派類型所指定的簽章時,委派才能代表方法。In the .NET Framework versions 1.0 and 1.1, a delegate can represent a method only if the signature of the method exactly matches the signature specified by the delegate type. 因此,只支援前述清單中的第一個和第三個專案符號,而第一個專案符號則需要完全相符的類型。Thus, only the first and third bullets in the preceding list are supported, and the first bullet requires an exact type match.

當委派代表透過其第一個引數關閉的實例方法時(最常見的案例),委派會儲存方法的進入點參考以及物件的參考,稱為目標,此類型可指派給定義了方法.When a delegate represents an instance method closed over its first argument (the most common case), the delegate stores a reference to the method's entry point and a reference to an object, called the target, which is of a type assignable to the type that defined the method. 當委派表示開放式實例方法時,它會儲存該方法的進入點參考。When a delegate represents an open instance method, it stores a reference to the method's entry point. 委派簽章必須在其型this式參數清單中包含隱藏的參數; 在此情況下,委派沒有目標物件的參考,而且叫用委派時必須提供目標物件。The delegate signature must include the hidden this parameter in its formal parameter list; in this case, the delegate does not have a reference to a target object, and a target object must be supplied when the delegate is invoked.

當委派代表靜態方法時,委派會儲存方法的進入點參考。When a delegate represents a static method, the delegate stores a reference to the method's entry point. 當委派代表在其第一個引數上關閉的靜態方法時,委派會儲存方法之進入點的參考,以及可指派給方法第一個引數之類型的目標物件參考。When a delegate represents a static method closed over its first argument, the delegate stores a reference to the method's entry point and a reference to a target object assignable to the type of the method's first argument. 叫用委派時,靜態方法的第一個引數會接收目標物件。When the delegate is invoked, the first argument of the static method receives the target object.

委派的調用清單是一組已排序的委派,其中清單的每個元素都只會叫用委派所代表的其中一個方法。The invocation list of a delegate is an ordered set of delegates in which each element of the list invokes exactly one of the methods represented by the delegate. 調用清單可以包含重複的方法。An invocation list can contain duplicate methods. 在叫用期間,會以它們出現在調用清單中的順序來叫用方法。During an invocation, methods are invoked in the order in which they appear in the invocation list. 委派會嘗試叫用其調用清單中的每個方法;重複專案會在每次出現在調用清單中時叫用一次。A delegate attempts to invoke every method in its invocation list; duplicates are invoked once for each time they appear in the invocation list. 委派是不可變的;建立之後,就不會變更委派的調用清單。Delegates are immutable; once created, the invocation list of a delegate does not change.

委派稱為多播或組合,因為委派可以叫用一或多個方法,並可用於合併作業。Delegates are referred to as multicast, or combinable, because a delegate can invoke one or more methods and can be used in combining operations.

結合作業(例如CombineRemove)不會改變現有的委派。Combining operations, such as Combine and Remove, do not alter existing delegates. 相反地,這類作業會傳回新的委派,其中包含作業的結果、未變更的委派null,或。Instead, such an operation returns a new delegate that contains the results of the operation, an unchanged delegate, or null. null當作業的結果是未參考至少一個方法的委派時,會傳回合並運算。A combining operation returns null when the result of the operation is a delegate that does not reference at least one method. 當要求的作業沒有作用時,結合作業會傳回未變更的委派。A combining operation returns an unchanged delegate when the requested operation has no effect.

注意

Managed 語言會使用CombineRemove方法來執行委派作業。Managed languages use the Combine and Remove methods to implement delegate operations. 範例包括 Visual Basic AddHandlerRemoveHandler的和語句,以及中C#委派類型的 + = 和-= 運算子。Examples include the AddHandler and RemoveHandler statements in Visual Basic and the += and -= operators on delegate types in C#.

從開始,泛型委派類型可以有 variant 類型參數。 .NET Framework 4.NET Framework 4Starting with the .NET Framework 4.NET Framework 4, generic delegate types can have variant type parameters. 逆變性型別參數可用來做為委派的參數型別,而「協變數型別參數」則可以當做傳回型別使用。Contravariant type parameters can be used as parameter types of the delegate, and a covariant type parameter can be used as the return type. 如果類型引數是具有繼承關聯性的參考型別,這項功能可讓從相同的泛型型別定義所建立的泛型委派類型與指派相容,如共變數和反變數中所述.This feature allows generic delegate types that are constructed from the same generic type definition to be assignment-compatible if their type arguments are reference types with an inheritance relationship, as explained in Covariance and Contravariance.

注意

與指派相容的泛型委派不一定是可組合的。Generic delegates that are assignment-compatible because of variance are not necessarily combinable. 若要進行組合,類型必須完全相符。To be combinable, the types must match exactly. 例如,假設名Derived為的類別衍生自名為Base的類別。For example, suppose that a class named Derived is derived from a class named Base. 類型Action<Base>的委派(Action(Of Base)在 Visual Basic 中)可以指派給類型Action<Derived>的變數,但因為類型不完全相符,所以無法結合這兩個委派。A delegate of type Action<Base> (Action(Of Base) in Visual Basic) can be assigned to a variable of type Action<Derived>, but the two delegates cannot be combined because the types do not match exactly.

如果叫用的方法擲回例外狀況,則方法會停止執行,並將例外狀況傳回給委派的呼叫者,而不會叫用調用清單中的剩餘方法。If an invoked method throws an exception, the method stops executing, the exception is passed back to the caller of the delegate, and remaining methods in the invocation list are not invoked. 攔截呼叫端中的例外狀況並不會改變此行為。Catching the exception in the caller does not alter this behavior.

當委派所叫用之方法的簽章包含傳回值時,委派會傳回檔用清單中最後一個元素的傳回值。When the signature of the methods invoked by a delegate includes a return value, the delegate returns the return value of the last element in the invocation list. 當簽章包含以傳址方式傳遞的參數時,參數的最後一個值會是調用清單中每個方法的結果,循序執行並更新參數的值。When the signature includes a parameter that is passed by reference, the final value of the parameter is the result of every method in the invocation list executing sequentially and updating the parameter's value.

與 C 中的委派最接近的對等是函式指標。The closest equivalent of a delegate in C is a function pointer. 委派可以代表靜態方法或實例方法。A delegate can represent a static method or an instance method. 當委派代表實例方法時,委派不僅會儲存對方法進入點的參考,也會存放類別實例的參考。When the delegate represents an instance method, the delegate stores not only a reference to the method's entry point, but also a reference to the class instance. 不同于函式指標,委派是物件導向且為型別安全。Unlike function pointers, delegates are object oriented and type safe.

建構函式

Delegate(Object, String)

初始化委派,這個委派會在指定的類別執行個體上叫用指定的執行個體方法。Initializes a delegate that invokes the specified instance method on the specified class instance.

Delegate(Type, String)

初始化委派,這個委派會從指定的類別叫用指定的靜態方法。Initializes a delegate that invokes the specified static method from the specified class.

屬性

Method

取得委派所表示的方法。Gets the method represented by the delegate.

Target

取得目前的委派用來叫用執行個體方法的類別執行個體。Gets the class instance on which the current delegate invokes the instance method.

方法

Clone()

建立委派的淺層複本 (Shallow Copy)。Creates a shallow copy of the delegate.

Combine(Delegate, Delegate)

串連兩個委派的引動過程清單。Concatenates the invocation lists of two delegates.

Combine(Delegate[])

串連委派陣列的引動過程清單。Concatenates the invocation lists of an array of delegates.

CombineImpl(Delegate)

串連指定的多點傳送 (可結合的) 委派和目前多點傳送 (可結合的) 委派的引動過程清單。Concatenates the invocation lists of the specified multicast (combinable) delegate and the current multicast (combinable) delegate.

CreateDelegate(Type, MethodInfo)

建立指定型別的委派來表示指定的靜態方法。Creates a delegate of the specified type to represent the specified static method.

CreateDelegate(Type, MethodInfo, Boolean)

建立指定之類型的委派,用來表示指定之靜態方法,並包含在繫結失敗時發生的指定之行為。Creates a delegate of the specified type to represent the specified static method, with the specified behavior on failure to bind.

CreateDelegate(Type, Object, MethodInfo)

建立指定之類型的委派,其表示指定之靜態或執行個體方法,並有指定第一個引數。Creates a delegate of the specified type that represents the specified static or instance method, with the specified first argument.

CreateDelegate(Type, Object, MethodInfo, Boolean)

建立指定之類型的委派,其表示指定之靜態或執行個體方法,並有指定第一個引數以及繫結失敗時所發生的行為。Creates a delegate of the specified type that represents the specified static or instance method, with the specified first argument and the specified behavior on failure to bind.

CreateDelegate(Type, Object, String)

建立指定類型的委派,這個委派表示要在指定的類別執行個體上叫用的指定執行個體方法。Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance.

CreateDelegate(Type, Object, String, Boolean)

建立指定型別的委派,這個委派表示要在指定的類別執行個體上,使用指定的大小寫區分來叫用的指定執行個體方法。Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance with the specified case-sensitivity.

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

建立指定之類型的委派,其表示要在指定的類別執行個體上叫用的指定執行個體方法,且會指定區分大小寫的方式以及在繫結失敗時要發生的行為。Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance, with the specified case-sensitivity and the specified behavior on failure to bind.

CreateDelegate(Type, Type, String)

建立指定類型的委派,這個委派表示指定類別的指定靜態方法。Creates a delegate of the specified type that represents the specified static method of the specified class.

CreateDelegate(Type, Type, String, Boolean)

建立指定之類型的委派,其表示指定之類別的指定靜態方法,且指定區分大小寫的方式。Creates a delegate of the specified type that represents the specified static method of the specified class, with the specified case-sensitivity.

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

建立指定之類型的委派,其表示指定之類別的指定靜態方法,且會指定區分大小寫的方式以及在繫結失敗時要發生的行為。Creates a delegate of the specified type that represents the specified static method of the specified class, with the specified case-sensitivity and the specified behavior on failure to bind.

DynamicInvoke(Object[])

動態叫用 (晚期繫結) 目前委派所表示的方法。Dynamically invokes (late-bound) the method represented by the current delegate.

DynamicInvokeImpl(Object[])

動態叫用 (晚期繫結) 目前委派所表示的方法。Dynamically invokes (late-bound) the method represented by the current delegate.

Equals(Object)

判斷指定的物件和目前的委派是否具有相同類型,並共用相同的目標、方法和引動過程清單。Determines whether the specified object and the current delegate are of the same type and share the same targets, methods, and invocation list.

GetHashCode()

傳回委派的雜湊碼。Returns a hash code for the delegate.

GetInvocationList()

傳回委派的引動過程清單。Returns the invocation list of the delegate.

GetMethodImpl()

取得目前委派所表示的靜態方法。Gets the static method represented by the current delegate.

GetObjectData(SerializationInfo, StreamingContext)

不支援。Not supported.

GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

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

從另一個委派的引動過程清單,移除委派的引動過程清單上最後一個項目。Removes the last occurrence of the invocation list of a delegate from the invocation list of another delegate.

RemoveAll(Delegate, Delegate)

從另一個委派的引動過程清單,移除委派的引動過程清單上所有的項目。Removes all occurrences of the invocation list of a delegate from the invocation list of another delegate.

RemoveImpl(Delegate)

從另一個委派的引動過程清單移除委派的引動過程清單。Removes the invocation list of a delegate from the invocation list of another delegate.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

運算子

Equality(Delegate, Delegate)

判斷指定的委派是否相等。Determines whether the specified delegates are equal.

Inequality(Delegate, Delegate)

判斷指定的委派是否不相等。Determines whether the specified delegates are not equal.

擴充方法

GetMethodInfo(Delegate)

取得表示特定委派所代表之方法的物件。Gets an object that represents the method represented by the specified delegate.

適用於

另請參閱