Delegate Delegate Delegate Delegate Class

定义

表示委托,委托是一种数据结构,它引用静态方法或引用类实例及该类的实例方法。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
继承
DelegateDelegateDelegateDelegate
派生
属性
实现

示例

下面的示例演示如何定义名为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. 实例方法的委托需要的mySampleClass实例。The 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.

公共语言运行时为每个委托类型BeginInvoke提供EndInvoke和方法,以启用委托的异步调用。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.

  • 类型的实例方法,其中的隐藏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中包含 hidden 参数; 在这种情况下,该委托不具有对目标对象的引用,并且在调用委托时必须提供目标对象。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. 相反,此类操作返回一个新委托,其中包含操作的结果、未更改的委托或nullInstead, 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.

备注

托管语言使用CombineRemove方法来实现委托操作。Managed languages use the Combine and Remove methods to implement delegate operations. 示例包括中AddHandlerRemoveHandler和语句 Visual Basic 和中C#的委托类型上的 + = 和-= 运算符。Examples include the AddHandler and RemoveHandler statements in Visual Basic and the += and -= operators on delegate types in C#.

从开始,泛型委托类型可以具有变体类型参数。 .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) Delegate(Object, String) Delegate(Object, String) Delegate(Object, String)

初始化一个委托,该委托对指定的类实例调用指定的实例方法。Initializes a delegate that invokes the specified instance method on the specified class instance.

Delegate(Type, String) Delegate(Type, String) Delegate(Type, String) Delegate(Type, String)

初始化一个委托,该委托从指定的类调用指定的静态方法。Initializes a delegate that invokes the specified static method from the specified class.

属性

Method Method Method Method

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

Target Target Target Target

获取类实例,当前委托将对其调用实例方法。Gets the class instance on which the current delegate invokes the instance method.

方法

Clone() Clone() Clone() Clone()

创建委托的浅表副本。Creates a shallow copy of the delegate.

Combine(Delegate, Delegate) Combine(Delegate, Delegate) Combine(Delegate, Delegate) Combine(Delegate, Delegate)

将两个委托的调用列表连接在一起。Concatenates the invocation lists of two delegates.

Combine(Delegate[]) Combine(Delegate[]) Combine(Delegate[]) Combine(Delegate[])

将委托数组的调用列表连接在一起。Concatenates the invocation lists of an array of delegates.

CombineImpl(Delegate) CombineImpl(Delegate) CombineImpl(Delegate) CombineImpl(Delegate)

将指定多路广播(可组合)委托和当前多路广播(可组合)委托的调用列表连接起来。Concatenates the invocation lists of the specified multicast (combinable) delegate and the current multicast (combinable) delegate.

CreateDelegate(Type, MethodInfo) CreateDelegate(Type, MethodInfo) CreateDelegate(Type, MethodInfo) CreateDelegate(Type, MethodInfo)

创建指定类型的委托以表示指定的静态方法。Creates a delegate of the specified type to represent the specified static method.

CreateDelegate(Type, MethodInfo, Boolean) CreateDelegate(Type, MethodInfo, Boolean) CreateDelegate(Type, MethodInfo, Boolean) 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) CreateDelegate(Type, Object, MethodInfo) CreateDelegate(Type, Object, MethodInfo) 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) CreateDelegate(Type, Object, MethodInfo, Boolean) CreateDelegate(Type, Object, MethodInfo, Boolean) 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) CreateDelegate(Type, Object, String) CreateDelegate(Type, Object, String) 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) CreateDelegate(Type, Object, String, Boolean) CreateDelegate(Type, Object, String, Boolean) 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) CreateDelegate(Type, Object, String, Boolean, Boolean) CreateDelegate(Type, Object, String, Boolean, Boolean) 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) CreateDelegate(Type, Type, String) CreateDelegate(Type, Type, String) 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) CreateDelegate(Type, Type, String, Boolean) CreateDelegate(Type, Type, String, Boolean) 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) CreateDelegate(Type, Type, String, Boolean, Boolean) CreateDelegate(Type, Type, String, Boolean, Boolean) 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[]) DynamicInvoke(Object[]) DynamicInvoke(Object[]) DynamicInvoke(Object[])

动态调用(后期绑定)由当前委托所表示的方法。Dynamically invokes (late-bound) the method represented by the current delegate.

DynamicInvokeImpl(Object[]) DynamicInvokeImpl(Object[]) DynamicInvokeImpl(Object[]) DynamicInvokeImpl(Object[])

动态调用(后期绑定)由当前委托所表示的方法。Dynamically invokes (late-bound) the method represented by the current delegate.

Equals(Object) Equals(Object) Equals(Object) 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() GetHashCode() GetHashCode() GetHashCode()

返回委托的哈希代码。Returns a hash code for the delegate.

GetInvocationList() GetInvocationList() GetInvocationList() GetInvocationList()

返回委托的调用列表。Returns the invocation list of the delegate.

GetMethodImpl() GetMethodImpl() GetMethodImpl() GetMethodImpl()

获取当前委托所表示的静态方法。Gets the static method represented by the current delegate.

GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

不支持。Not supported.

GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(Delegate, Delegate) Remove(Delegate, Delegate) Remove(Delegate, Delegate) Remove(Delegate, Delegate)

从一个委托的调用列表中移除另一个委托的最后一个调用列表。Removes the last occurrence of the invocation list of a delegate from the invocation list of another delegate.

RemoveAll(Delegate, Delegate) RemoveAll(Delegate, Delegate) RemoveAll(Delegate, Delegate) RemoveAll(Delegate, Delegate)

从一个委托的调用列表中移除另一个委托的所有调用列表。Removes all occurrences of the invocation list of a delegate from the invocation list of another delegate.

RemoveImpl(Delegate) RemoveImpl(Delegate) RemoveImpl(Delegate) RemoveImpl(Delegate)

从一个委托的调用列表中移除另一个委托的调用列表。Removes the invocation list of a delegate from the invocation list of another delegate.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

操作员

Equality(Delegate, Delegate) Equality(Delegate, Delegate) Equality(Delegate, Delegate) Equality(Delegate, Delegate)

确定指定的委托是否相等。Determines whether the specified delegates are equal.

Inequality(Delegate, Delegate) Inequality(Delegate, Delegate) Inequality(Delegate, Delegate) Inequality(Delegate, Delegate)

确定指定的委托是否相等。Determines whether the specified delegates are not equal.

扩展方法

GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate)

获取指示指定委托表示的方法的对象。Gets an object that represents the method represented by the specified delegate.

适用于

另请参阅