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
派生
属性
实现

示例

下面的示例演示如何定义一个名为的委托myMethodDelegateThe 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. mySampleClass实例保存在名为mySCThe 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 "".
*/ 

Imports System

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 'mySampleClass

   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 'Main

End Class 'SamplesDelegate 


'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 或 Visual 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. 有关这些方法的详细信息,请参阅Calling Synchronous Methods AsynchronouslyFor 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参数在其形参表; 在这种情况下,委托不具有对目标对象的引用和调用委托时,必须提供目标对象。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 4,泛型委托类型可以具有 variant 类型参数。Starting 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派生的类名为BaseFor 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.

Extension Methods

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

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

适用于

另请参阅