Delegate.CreateDelegate Método

Definición

Crea un delegado del tipo especificado.Creates a delegate of the specified type.

Sobrecargas

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

Crea un delegado del tipo especificado que representa el método estático determinado de la clase especificada, con la distinción de mayúsculas y minúsculas definida y el comportamiento que se haya concretado para cuando se produce un error al enlazar.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.

CreateDelegate(Type, Type, String, Boolean)

Crea un delegado del tipo especificado que representa el método estático determinado de la clase especificada, con la distinción de mayúsculas y minúsculas definida.Creates a delegate of the specified type that represents the specified static method of the specified class, with the specified case-sensitivity.

CreateDelegate(Type, Object, String, Boolean)

Crea un delegado del tipo especificado que representa el método de instancia especificado que se va a invocar en la instancia de clase especificada con la distinción de mayúsculas y minúsculas que se haya especificado.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, MethodInfo, Boolean)

Crea un delegado del tipo especificado que representa el método estático o de instancia determinado, con el primer argumento definido y el comportamiento especificado si se produce un error en el enlace.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, Boolean, Boolean)

Crea un delegado del tipo especificado que representa el método de instancia determinado que se va a invocar en la instancia de clase especificada, con la distinción de mayúsculas y minúsculas y el comportamiento que se hayan concretado para cuando se produce un error al enlazar.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, MethodInfo, Boolean)

Crea un delegado del tipo especificado para representar el método estático especificado, con el comportamiento establecido para el caso de que se produzca un error al enlazar.Creates a delegate of the specified type to represent the specified static method, with the specified behavior on failure to bind.

CreateDelegate(Type, Object, String)

Crea un delegado del tipo especificado que representa el método de instancia especificado que se va a invocar en la instancia de clase especificada.Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance.

CreateDelegate(Type, Object, MethodInfo)

Crea un delegado del tipo especificado que representa el método estático o de instancia especificado, con el primer argumento definido.Creates a delegate of the specified type that represents the specified static or instance method, with the specified first argument.

CreateDelegate(Type, Type, String)

Crea un delegado del tipo especificado que representa el método estático especificado de la clase especificada.Creates a delegate of the specified type that represents the specified static method of the specified class.

CreateDelegate(Type, MethodInfo)

Crea un delegado del tipo especificado para representar el método estático especificado.Creates a delegate of the specified type to represent the specified static method.

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

Crea un delegado del tipo especificado que representa el método estático determinado de la clase especificada, con la distinción de mayúsculas y minúsculas definida y el comportamiento que se haya concretado para cuando se produce un error al enlazar.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.

public:
 static Delegate ^ CreateDelegate(Type ^ type, Type ^ target, System::String ^ method, bool ignoreCase, bool throwOnBindFailure);
public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure);
static member CreateDelegate : Type * Type * string * bool * bool -> Delegate

Parámetros

type
Type

Type de delegado que se va a crear.The Type of delegate to create.

target
Type

Type que representa la clase que implementa method.The Type representing the class that implements method.

method
String

Nombre del método estático que va a representar el delegado.The name of the static method that the delegate is to represent.

ignoreCase
Boolean

Valor booleano que indica si debe omitirse la distinción de mayúsculas y minúsculas al comparar el nombre del método.A Boolean indicating whether to ignore the case when comparing the name of the method.

throwOnBindFailure
Boolean

Es true para iniciar una excepción si no se puede enlazar method; en caso contrario, es false.true to throw an exception if method cannot be bound; otherwise, false.

Devoluciones

Delegado del tipo especificado que representa el método estático especificado de la clase especificada.A delegate of the specified type that represents the specified static method of the specified class.

Excepciones

type es null.type is null.

O bien-or- target es null.target is null.

O bien-or- method es null.method is null.

type no hereda MulticastDelegate.type does not inherit MulticastDelegate.

O bien-or- type no es un RuntimeType.type is not a RuntimeType. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

O bien-or- target no es un RuntimeType.target is not a RuntimeType.

O bien-or- target es un tipo genérico abierto.target is an open generic type. Es decir, su propiedad ContainsGenericParameters es true.That is, its ContainsGenericParameters property is true.

o bien-or- method no es un método static (método Shared en Visual Basic).method is not a static method (Shared method in Visual Basic).

O bien-or- method no se puede enlazar (por ejemplo, porque no se encuentra) y throwOnBindFailure es true.method cannot be bound, for example because it cannot be found, and throwOnBindFailure is true.

No se encuentra el método Invoke de type.The Invoke method of type is not found.

El autor de la llamada no tiene los permisos necesarios para acceder a method.The caller does not have the permissions necessary to access method.

Comentarios

Este método solo crea delegados para métodos estáticos.This method creates delegates for static methods only. Un método de instancia es un método que está asociado a una instancia de una clase; un método estático es un método que está asociado a la propia clase.An instance method is a method that is associated with an instance of a class; a static method is a method that is associated with the class itself.

Nota

A partir de ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess , este método se puede usar para tener acceso a métodos no públicos si el llamador se ha concedido con la marca y si el conjunto de permisos de los métodos no públicos está restringido al conjunto de permisos del llamador o a un .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1subconjunto. mismo.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public methods if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public methods is restricted to the caller's grant set, or a subset thereof. (Consulte consideraciones de seguridad para la reflexión).(See Security Considerations for Reflection.)

Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Seguridad

ReflectionPermission
Cuando se invoca enlazado en tiempo de ejecución mediante InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])mecanismos como.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Consulte también:

CreateDelegate(Type, Type, String, Boolean)

Crea un delegado del tipo especificado que representa el método estático determinado de la clase especificada, con la distinción de mayúsculas y minúsculas definida.Creates a delegate of the specified type that represents the specified static method of the specified class, with the specified case-sensitivity.

public:
 static Delegate ^ CreateDelegate(Type ^ type, Type ^ target, System::String ^ method, bool ignoreCase);
public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase);
static member CreateDelegate : Type * Type * string * bool -> Delegate

Parámetros

type
Type

Type de delegado que se va a crear.The Type of delegate to create.

target
Type

Type que representa la clase que implementa method.The Type representing the class that implements method.

method
String

Nombre del método estático que va a representar el delegado.The name of the static method that the delegate is to represent.

ignoreCase
Boolean

Valor booleano que indica si debe omitirse la distinción de mayúsculas y minúsculas al comparar el nombre del método.A Boolean indicating whether to ignore the case when comparing the name of the method.

Devoluciones

Delegado del tipo especificado que representa el método estático especificado de la clase especificada.A delegate of the specified type that represents the specified static method of the specified class.

Excepciones

type es null.type is null.

O bien-or- target es null.target is null.

o bien-or- method es null.method is null.

type no hereda MulticastDelegate.type does not inherit MulticastDelegate.

O bien-or- type no es un RuntimeType.type is not a RuntimeType. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

o bien-or- target no es un RuntimeType.target is not a RuntimeType.

o bien-or- target es un tipo genérico abierto.target is an open generic type. Es decir, su propiedad ContainsGenericParameters es true.That is, its ContainsGenericParameters property is true.

o bien-or- method no es un método static (método Shared en Visual Basic).method is not a static method (Shared method in Visual Basic).

O bien-or- method no se puede enlazar, por ejemplo, porque no se encuentra.method cannot be bound, for example because it cannot be found.

No se encuentra el método Invoke de type.The Invoke method of type is not found.

El autor de la llamada no tiene los permisos necesarios para acceder a method.The caller does not have the permissions necessary to access method.

Comentarios

Este método solo crea delegados para métodos estáticos.This method creates delegates for static methods only. Un método de instancia es un método que está asociado a una instancia de una clase; un método estático es un método que está asociado a la propia clase.An instance method is a method that is associated with an instance of a class; a static method is a method that is associated with the class itself.

Esta sobrecarga del método es equivalente a llamar CreateDelegate(Type, Type, String, Boolean, Boolean) a la sobrecarga del método true , throwOnBindFailureespecificando para.This method overload is equivalent to calling the CreateDelegate(Type, Type, String, Boolean, Boolean) method overload, specifying true for throwOnBindFailure.

Nota

A partir de ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess , este método se puede usar para tener acceso a métodos no públicos si el llamador se ha concedido con la marca y si el conjunto de permisos de los métodos no públicos está restringido al conjunto de permisos del llamador o a un .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1subconjunto. mismo.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public methods if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public methods is restricted to the caller's grant set, or a subset thereof. (Consulte consideraciones de seguridad para la reflexión).(See Security Considerations for Reflection.)

Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Seguridad

ReflectionPermission
Cuando se invoca enlazado en tiempo de ejecución mediante InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])mecanismos como.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Consulte también:

CreateDelegate(Type, Object, String, Boolean)

Crea un delegado del tipo especificado que representa el método de instancia especificado que se va a invocar en la instancia de clase especificada con la distinción de mayúsculas y minúsculas que se haya especificado.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.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ target, System::String ^ method, bool ignoreCase);
public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase);
static member CreateDelegate : Type * obj * string * bool -> Delegate

Parámetros

type
Type

Type de delegado que se va a crear.The Type of delegate to create.

target
Object

Instancia de clase en la que se invoca a method.The class instance on which method is invoked.

method
String

Nombre del método de instancia que el delegado va a representar.The name of the instance method that the delegate is to represent.

ignoreCase
Boolean

Valor booleano que indica si debe omitirse la distinción de mayúsculas y minúsculas al comparar el nombre del método.A Boolean indicating whether to ignore the case when comparing the name of the method.

Devoluciones

Delegado del tipo especificado que representa el método de instancia especificado que se va a invocar en la instancia de clase especificada.A delegate of the specified type that represents the specified instance method to invoke on the specified class instance.

Excepciones

type es null.type is null.

O bien-or- target es null.target is null.

o bien-or- method es null.method is null.

type no hereda MulticastDelegate.type does not inherit MulticastDelegate.

O bien-or- type no es un RuntimeType.type is not a RuntimeType. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

O bien-or- method no es un método de instancia.method is not an instance method.

o bien-or- method no se puede enlazar, por ejemplo, porque no se encuentra.method cannot be bound, for example because it cannot be found.

No se encuentra el método Invoke de type.The Invoke method of type is not found.

El autor de la llamada no tiene los permisos necesarios para acceder a method.The caller does not have the permissions necessary to access method.

Comentarios

Este método solo crea los delegados para los métodos de instancia.This method creates delegates for instance methods only. Un método de instancia es un método que está asociado a una instancia de una clase; un método estático es un método que está asociado a la propia clase.An instance method is a method that is associated with an instance of a class; a static method is a method that is associated with the class itself.

Esta sobrecarga del método es equivalente a llamar CreateDelegate(Type, Object, String, Boolean, Boolean) a la sobrecarga del método true , throwOnBindFailureespecificando para.This method overload is equivalent to calling the CreateDelegate(Type, Object, String, Boolean, Boolean) method overload, specifying true for throwOnBindFailure.

Nota

A partir de ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess , este método se puede usar para tener acceso a métodos no públicos si el llamador se ha concedido con la marca y si el conjunto de permisos de los métodos no públicos está restringido al conjunto de permisos del llamador o a un .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1subconjunto. mismo.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public methods if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public methods is restricted to the caller's grant set, or a subset thereof. (Consulte consideraciones de seguridad para la reflexión).(See Security Considerations for Reflection.)

Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Seguridad

ReflectionPermission
Cuando se invoca enlazado en tiempo de ejecución mediante InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])mecanismos como.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Consulte también:

CreateDelegate(Type, Object, MethodInfo, Boolean)

Crea un delegado del tipo especificado que representa el método estático o de instancia determinado, con el primer argumento definido y el comportamiento especificado si se produce un error en el enlace.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.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ firstArgument, System::Reflection::MethodInfo ^ method, bool throwOnBindFailure);
public static Delegate CreateDelegate (Type type, object firstArgument, System.Reflection.MethodInfo method, bool throwOnBindFailure);
static member CreateDelegate : Type * obj * System.Reflection.MethodInfo * bool -> Delegate

Parámetros

type
Type

Type que representa el tipo de delegado que se va a crear.A Type representing the type of delegate to create.

firstArgument
Object

Object que es el primer argumento del método que representa el delegado.An Object that is the first argument of the method the delegate represents. Para los métodos de instancia, debe ser compatible con el tipo de instancia.For instance methods, it must be compatible with the instance type.

method
MethodInfo

MethodInfo que describe el método estático o de instancia que el delegado va a representar.The MethodInfo describing the static or instance method the delegate is to represent.

throwOnBindFailure
Boolean

Es true para iniciar una excepción si no se puede enlazar method; en caso contrario, es false.true to throw an exception if method cannot be bound; otherwise, false.

Devoluciones

Delegado del tipo especificado que representa el método estático o de instancia determinado, o null si throwOnBindFailure es false y no se puede enlazar el delegado a method.A delegate of the specified type that represents the specified static or instance method, or null if throwOnBindFailure is false and the delegate cannot be bound to method.

Excepciones

type es null.type is null.

o bien-or- method es null.method is null.

type no hereda MulticastDelegate.type does not inherit MulticastDelegate.

o bien-or- type no es un RuntimeType.type is not a RuntimeType. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

o bien-or- No se puede enlazar method y throwOnBindFailure es true.method cannot be bound, and throwOnBindFailure is true.

o bien-or- method no es un RuntimeMethodInfo.method is not a RuntimeMethodInfo. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

No se encuentra el método Invoke de type.The Invoke method of type is not found.

El autor de la llamada no tiene los permisos necesarios para acceder a method.The caller does not have the permissions necessary to access method.

Ejemplos

Esta sección contiene tres ejemplos de código.This section contains three code examples. En el primer ejemplo se muestran los cuatro tipos de delegados que se pueden crear: cerrados en un método de instancia, abrir sobre un método de instancia, abrir sobre un método estático y cerrar en un método estático.The first example demonstrates the four kinds of delegates that can be created: closed over an instance method, open over an instance method, open over a static method, and closed over a static method.

En el segundo ejemplo de código se muestran los tipos de parámetros compatibles y los tipos de valor devueltos.The second code example demonstrates compatible parameter types and return types.

En el tercer ejemplo de código se define un tipo de delegado único y se muestran todos los métodos que el tipo de delegado puede representar.The third code example defines a single delegate type, and shows all the methods that delegate type can represent.

Ejemplo 1Example 1

En el ejemplo de código siguiente se muestran las cuatro maneras en que se puede crear un delegado CreateDelegate mediante esta sobrecarga del método.The following code example demonstrates the four ways a delegate can be created using this overload of the CreateDelegate method.

Nota

Hay dos sobrecargas del CreateDelegate método que especifican firstArgument y MethodInfo, su funcionalidad es la misma, salvo que una permite especificar si se va a producir un error al enlazar y la otra siempre produce una excepción.There are two overloads of the CreateDelegate method that specify firstArgument and a MethodInfo; their functionality is the same except that one allows you to specify whether to throw on failure to bind, and the other always throws. En este ejemplo de código se usan las dos sobrecargas.This code example uses both overloads.

En el ejemplo se declara una C clase con un método M2 estático y un método M1de instancia, y tres tipos D1 de delegado: toma C una instancia de y D2 una cadena, toma una cadena y D3no tiene argumentos.The example declares a class C with a static method M2 and an instance method M1, and three delegate types: D1 takes an instance of C and a string, D2 takes a string, and D3 has no arguments.

Una segunda clase denominada Example contiene el código que crea los delegados.A second class named Example contains the code that creates the delegates.

  • Se crea un delegado D2de tipo, cerrado en una Cinstancia de, para el método M1de instancia.A delegate of type D2, closed over an instance of C, is created for the instance method M1. Se invoca con cadenas diferentes para mostrar que siempre se usa la instancia enlazada C de.It is invoked with different strings, to show that the bound instance of C is always used.

  • Se crea un delegado D1de tipo, que representa un método de instancia abierto, para el M1método de instancia.A delegate of type D1, representing an open instance method, is created for the instance method M1. Se debe pasar una instancia de cuando se invoca el delegado.An instance must be passed when the delegate is invoked.

  • Se crea un delegado D2de tipo que representa un método estático abierto para el método M2estático.A delegate of type D2, representing an open static method, is created for the static method M2.

  • Por último, se crea un D3delegado de tipo, cerrado en una cadena, para el método M2estático.Finally, a delegate of type D3, closed over a string, is created for the static method M2. El método se invoca para mostrar que usa la cadena enlazada.The method is invoked to show that it uses the bound string.

using System;
using System.Reflection;
using System.Security.Permissions;

// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();

// A sample class with an instance method and a static method.
//
public class C
{
    private int id;
    public C(int id) { this.id = id; }

    public void M1(string s) 
    { 
        Console.WriteLine("Instance method M1 on C:  id = {0}, s = {1}",
            this.id, s);
    }
  
    public static void M2(string s)
    { 
        Console.WriteLine("Static method M2 on C:  s = {0}", s); 
    }
}

public class Example
{
    public static void Main()
    {
        C c1 = new C(42);

        // Get a MethodInfo for each method.
        //
        MethodInfo mi1 = typeof(C).GetMethod("M1", 
            BindingFlags.Public | BindingFlags.Instance);
        MethodInfo mi2 = typeof(C).GetMethod("M2",
            BindingFlags.Public | BindingFlags.Static);

        D1 d1;
        D2 d2;
        D3 d3;


        Console.WriteLine("\nAn instance method closed over C.");
        // In this case, the delegate and the
        // method must have the same list of argument types; use
        // delegate type D2 with instance method M1.
        //
        Delegate test = 
            Delegate.CreateDelegate(typeof(D2), c1, mi1, false);

        // Because false was specified for throwOnBindFailure 
        // in the call to CreateDelegate, the variable 'test'
        // contains null if the method fails to bind (for 
        // example, if mi1 happened to represent a method of  
        // some class other than C).
        //
        if (test != null)
        {
            d2 = (D2) test;

            // The same instance of C is used every time the 
            // delegate is invoked.
            d2("Hello, World!");
            d2("Hi, Mom!");
        }


        Console.WriteLine("\nAn open instance method.");
        // In this case, the delegate has one more 
        // argument than the instance method; this argument comes
        // at the beginning, and represents the hidden instance
        // argument of the instance method. Use delegate type D1
        // with instance method M1.
        //
        d1 = (D1) Delegate.CreateDelegate(typeof(D1), null, mi1);

        // An instance of C must be passed in each time the 
        // delegate is invoked.
        //
        d1(c1, "Hello, World!");
        d1(new C(5280), "Hi, Mom!");


        Console.WriteLine("\nAn open static method.");
        // In this case, the delegate and the method must 
        // have the same list of argument types; use delegate type
        // D2 with static method M2.
        //
        d2 = (D2) Delegate.CreateDelegate(typeof(D2), null, mi2);

        // No instances of C are involved, because this is a static
        // method. 
        //
        d2("Hello, World!");
        d2("Hi, Mom!");


        Console.WriteLine("\nA static method closed over the first argument (String).");
        // The delegate must omit the first argument of the method.
        // A string is passed as the firstArgument parameter, and 
        // the delegate is bound to this string. Use delegate type 
        // D3 with static method M2. 
        //
        d3 = (D3) Delegate.CreateDelegate(typeof(D3), 
            "Hello, World!", mi2);

        // Each time the delegate is invoked, the same string is
        // used.
        d3();
    }
}

/* This code example produces the following output:

An instance method closed over C.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 42, s = Hi, Mom!

An open instance method.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 5280, s = Hi, Mom!

An open static method.
Static method M2 on C:  s = Hello, World!
Static method M2 on C:  s = Hi, Mom!

A static method closed over the first argument (String).
Static method M2 on C:  s = Hello, World!
 */
Imports System.Reflection
Imports System.Security.Permissions

' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C, ByVal s As String) 
Public Delegate Sub D2(ByVal s As String) 
Public Delegate Sub D3() 

' A sample class with an instance method and a Shared method.
'
Public Class C
    Private id As Integer
    Public Sub New(ByVal id As Integer) 
        Me.id = id
    End Sub

    Public Sub M1(ByVal s As String) 
        Console.WriteLine("Instance method M1 on C:  id = {0}, s = {1}", _
            Me.id, s)
    End Sub
    
    Public Shared Sub M2(ByVal s As String) 
        Console.WriteLine("Shared method M2 on C:  s = {0}", s)
    End Sub
End Class

Public Class Example
    
    Public Shared Sub Main() 

        Dim c1 As New C(42)
        
        ' Get a MethodInfo for each method.
        '
        Dim mi1 As MethodInfo = GetType(C).GetMethod("M1", _
            BindingFlags.Public Or BindingFlags.Instance)
        Dim mi2 As MethodInfo = GetType(C).GetMethod("M2", _
            BindingFlags.Public Or BindingFlags.Static)
        
        Dim d1 As D1
        Dim d2 As D2
        Dim d3 As D3
        
        
        Console.WriteLine(vbLf & "An instance method closed over C.")
        ' In this case, the delegate and the
        ' method must have the same list of argument types; use
        ' delegate type D2 with instance method M1.
        '
        Dim test As [Delegate] = _
            [Delegate].CreateDelegate(GetType(D2), c1, mi1, False)

        ' Because False was specified for throwOnBindFailure 
        ' in the call to CreateDelegate, the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if mi1 happened to represent a method of 
        ' some class other than C).
        '
        If test IsNot Nothing Then
            d2 = CType(test, D2)

            ' The same instance of C is used every time the
            ' delegate is invoked.
            d2("Hello, World!")
            d2("Hi, Mom!")
        End If
        
        
        Console.WriteLine(vbLf & "An open instance method.")
        ' In this case, the delegate has one more 
        ' argument than the instance method; this argument comes
        ' at the beginning, and represents the hidden instance
        ' argument of the instance method. Use delegate type D1
        ' with instance method M1.
        '
        d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)
        
        ' An instance of C must be passed in each time the 
        ' delegate is invoked.
        '
        d1(c1, "Hello, World!")
        d1(New C(5280), "Hi, Mom!")
        
        
        Console.WriteLine(vbLf & "An open Shared method.")
        ' In this case, the delegate and the method must 
        ' have the same list of argument types; use delegate type
        ' D2 with Shared method M2.
        '
        d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)
        
        ' No instances of C are involved, because this is a Shared
        ' method. 
        '
        d2("Hello, World!")
        d2("Hi, Mom!")
        
        
        Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
        ' The delegate must omit the first argument of the method.
        ' A string is passed as the firstArgument parameter, and 
        ' the delegate is bound to this string. Use delegate type 
        ' D3 with Shared method M2. 
        '
        d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)
        
        ' Each time the delegate is invoked, the same string is
        ' used.
        d3()
    
    End Sub
End Class

' This code example produces the following output:
'
'An instance method closed over C.
'Instance method M1 on C:  id = 42, s = Hello, World!
'Instance method M1 on C:  id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C:  id = 42, s = Hello, World!
'Instance method M1 on C:  id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C:  s = Hello, World!
'Shared method M2 on C:  s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C:  s = Hello, World!
' 

Ejemplo 2Example 2

En el ejemplo de código siguiente se muestra la compatibilidad de los tipos de parámetro y los tipos de valor devuelto.The following code example demonstrates compatibility of parameter types and return types.

Nota

En este ejemplo de código CreateDelegate(Type, MethodInfo) se usa la sobrecarga del método.This code example uses the CreateDelegate(Type, MethodInfo) method overload. El uso de otras sobrecargas que toman MethodInfo es similar.The use of other overloads that take MethodInfo is similar.

En el ejemplo de código se define una Base clase base denominada y Derived una clase denominada que Basese deriva de.The code example defines a base class named Base and a class named Derived that derives from Base. La clase derivada tiene un static métodoShared (en Visual Basic) denominado MyMethod con un parámetro de tipo Base y un tipo de valor Deriveddevuelto de.The derived class has a static (Shared in Visual Basic) method named MyMethod with one parameter of type Base and a return type of Derived. En el ejemplo de código también se define Example un delegado denominado que tiene un Derived parámetro de tipo y un Basetipo de valor devuelto de.The code example also defines a delegate named Example that has one parameter of type Derived and a return type of Base.

En el ejemplo de código se muestra que Example el delegado denominado se puede usar para MyMethodrepresentar el método.The code example demonstrates that the delegate named Example can be used to represent the method MyMethod. El método se puede enlazar al delegado porque:The method can be bound to the delegate because:

  • El tipo de parámetro del delegado (Derived) es más restrictivo que el tipo de parámetro de MyMethod (Base), de modo que siempre es seguro pasar el argumento del delegado a MyMethod.The parameter type of the delegate (Derived) is more restrictive than the parameter type of MyMethod (Base), so that it is always safe to pass the argument of the delegate to MyMethod.

  • El tipo de valor MyMethod devuelto de (Derived) es más restrictivo que el tipo de parámetro delBasedelegado (), de modo que siempre es seguro convertir el tipo de valor devuelto del método al tipo de valor devuelto del delegado.The return type of MyMethod (Derived) is more restrictive than the parameter type of the delegate (Base), so that it is always safe to cast the return type of the method to the return type of the delegate.

El ejemplo de código no genera ningún resultado.The code example produces no output.

using namespace System;
using namespace System::Reflection;

// Define two classes to use in the demonstration, a base class and 
// a class that derives from it.
//
public ref class Base {};

public ref class Derived : Base
{
    // Define a static method to use in the demonstration. The method 
    // takes an instance of Base and returns an instance of Derived.  
    // For the purposes of the demonstration, it is not necessary for 
    // the method to do anything useful. 
    //
public:
    static Derived^ MyMethod(Base^ arg)
    {
        Base^ dummy = arg;
        return gcnew Derived();
    }
};

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base^ Example(Derived^ arg);

void main()
{
    // The binding flags needed to retrieve MyMethod.
    BindingFlags flags = BindingFlags::Public | BindingFlags::Static;

    // Get a MethodInfo that represents MyMethod.
    MethodInfo^ minfo = Derived::typeid->GetMethod("MyMethod", flags);

    // Demonstrate contravariance of parameter types and covariance
    // of return types by using the delegate Example to represent
    // MyMethod. The delegate binds to the method because the
    // parameter of the delegate is more restrictive than the 
    // parameter of the method (that is, the delegate accepts an
    // instance of Derived, which can always be safely passed to
    // a parameter of type Base), and the return type of MyMethod
    // is more restrictive than the return type of Example (that
    // is, the method returns an instance of Derived, which can
    // always be safely cast to type Base). 
    //
    Example^ ex = 
        (Example^) Delegate::CreateDelegate(Example::typeid, minfo);

    // Execute MyMethod using the delegate Example.
    //        
    Base^ b = ex(gcnew Derived());
}
using System;
using System.Reflection;

// Define two classes to use in the demonstration, a base class and 
// a class that derives from it.
//
public class Base {}

public class Derived : Base
{
    // Define a static method to use in the demonstration. The method 
    // takes an instance of Base and returns an instance of Derived.  
    // For the purposes of the demonstration, it is not necessary for 
    // the method to do anything useful. 
    //
    public static Derived MyMethod(Base arg)
    {
        Base dummy = arg;
        return new Derived();
    }
}

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example(Derived arg);

class Test
{
    public static void Main()
    {
        // The binding flags needed to retrieve MyMethod.
        BindingFlags flags = BindingFlags.Public | BindingFlags.Static;

        // Get a MethodInfo that represents MyMethod.
        MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);

        // Demonstrate contravariance of parameter types and covariance
        // of return types by using the delegate Example to represent
        // MyMethod. The delegate binds to the method because the
        // parameter of the delegate is more restrictive than the 
        // parameter of the method (that is, the delegate accepts an
        // instance of Derived, which can always be safely passed to
        // a parameter of type Base), and the return type of MyMethod
        // is more restrictive than the return type of Example (that
        // is, the method returns an instance of Derived, which can
        // always be safely cast to type Base). 
        //
        Example ex = 
            (Example) Delegate.CreateDelegate(typeof(Example), minfo);

        // Execute MyMethod using the delegate Example.
        //        
        Base b = ex(new Derived());
    }
}
Imports System.Reflection

' Define two classes to use in the demonstration, a base class and 
' a class that derives from it.
'
Public Class Base
End Class

Public Class Derived
    Inherits Base

    ' Define a Shared method to use in the demonstration. The method 
    ' takes an instance of Base and returns an instance of Derived.  
    ' For the purposes of the demonstration, it is not necessary for 
    ' the method to do anything useful. 
    '
    Public Shared Function MyMethod(ByVal arg As Base) As Derived
        Dim dummy As Base = arg
        Return New Derived()
    End Function

End Class

' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base

Module Test

    Sub Main()

        ' The binding flags needed to retrieve MyMethod.
        Dim flags As BindingFlags = _
            BindingFlags.Public Or BindingFlags.Static

        ' Get a MethodInfo that represents MyMethod.
        Dim minfo As MethodInfo = _
            GetType(Derived).GetMethod("MyMethod", flags)

        ' Demonstrate contravariance of parameter types and covariance
        ' of return types by using the delegate Example to represent
        ' MyMethod. The delegate binds to the method because the
        ' parameter of the delegate is more restrictive than the 
        ' parameter of the method (that is, the delegate accepts an
        ' instance of Derived, which can always be safely passed to
        ' a parameter of type Base), and the return type of MyMethod
        ' is more restrictive than the return type of Example (that
        ' is, the method returns an instance of Derived, which can
        ' always be safely cast to type Base). 
        '
        Dim ex As Example = CType( _
            [Delegate].CreateDelegate(GetType(Example), minfo), _
            Example _
        )

        ' Execute MyMethod using the delegate Example.
        '        
        Dim b As Base = ex(New Derived())
    End Sub
End Module

Ejemplo 3Example 3

En el ejemplo de código siguiente se muestran todos los métodos que un único tipo de delegado puede representar.The following code example shows all the methods a single delegate type can represent.

Nota

Hay dos sobrecargas del CreateDelegate método que especifican firstArgument y MethodInfo, su funcionalidad es la misma, salvo que una permite especificar si se va a producir un error al enlazar y la otra siempre produce una excepción.There are two overloads of the CreateDelegate method that specify firstArgument and a MethodInfo; their functionality is the same except that one allows you to specify whether to throw on failure to bind, and the other always throws. En este ejemplo de código se usan las dos sobrecargas.This code example uses both overloads.

En el ejemplo de código se definen C dos Fclases, y, y D un tipo de delegado con Cun argumento de tipo.The code example defines two classes, C and F, and a delegate type D with one argument of type C. Las clases M1tienen métodos estáticos y de instancia coincidentes, M3, C y M4, y la clase M2 también tiene un método de instancia que no tiene argumentos.The classes have matching static and instance methods M1, M3, and M4, and class C also has an instance method M2 that has no arguments.

Una tercera clase denominada Example contiene el código que crea los delegados.A third class named Example contains the code that creates the delegates.

  • Los delegados se crean M1 para el C método de Finstancia de tipo y tipo; cada uno se cierra en una instancia del tipo respectivo.Delegates are created for instance method M1 of type C and type F; each is closed over an instance of the respective type. El M1 método de C tipo muestra ID las propiedades de la instancia enlazada y del argumento.Method M1 of type C displays the ID properties of the bound instance and of the argument.

  • Se crea un delegado para el M2 método de Ctipo.A delegate is created for method M2 of type C. Se trata de un delegado de instancia abierto, en el que el argumento del delegado representa el primer argumento oculto en el método de instancia.This is an open instance delegate, in which the argument of the delegate represents the hidden first argument on the instance method. El método no tiene ningún otro argumento.The method has no other arguments.

  • Los delegados se crean M3 para el C método estático Fde tipo y tipo; son delegados estáticos abiertos.Delegates are created for static method M3 of type C and type F; these are open static delegates.

  • Por último, los delegados se M4 crean para C el método Festático de tipo y tipo; cada método tiene el tipo declarativo como primer argumento y se proporciona una instancia del tipo, por lo que los delegados se cierran en sus primeros argumentos. .Finally, delegates are created for static method M4 of type C and type F; each method has the declaring type as its first argument, and an instance of the type is supplied, so the delegates are closed over their first arguments. El M4 método de C tipo muestra ID las propiedades de la instancia enlazada y del argumento.Method M4 of type C displays the ID properties of the bound instance and of the argument.

using System;
using System.Reflection;
using System.Security.Permissions;

// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
//
public delegate void D(C c);

// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
//
public class C
{
    private int id;
    public int ID { get { return id; }}
    public C(int id) { this.id = id; }

    public void M1(C c) 
    { 
        Console.WriteLine("Instance method M1(C c) on C:  this.id = {0}, c.ID = {1}",
            this.id, c.ID);
    }
  
    public void M2() 
    { 
        Console.WriteLine("Instance method M2() on C:  this.id = {0}",
            this.id);
    }
  
    public static void M3(C c)
    { 
        Console.WriteLine("Static method M3(C c) on C:  c.ID = {0}", c.ID); 
    }

    public static void M4(C c1, C c2) 
    { 
        Console.WriteLine("Static method M4(C c1, C c2) on C:  c1.ID = {0}, c2.ID = {1}",
            c1.ID, c2.ID);
    }
}

public class F
{
    public void M1(C c) 
    { 
        Console.WriteLine("Instance method M1(C c) on F:  c.ID = {0}",
            c.ID);
    }
  
    public static void M3(C c)
    { 
        Console.WriteLine("Static method M3(C c) on F:  c.ID = {0}", c.ID); 
    }

    public static void M4(F f, C c) 
    { 
        Console.WriteLine("Static method M4(F f, C c) on F:  c.ID = {0}",
            c.ID);
    }
}


public class Example
{
    public static void Main()
    {
        C c1 = new C(42);
        C c2 = new C(1491);
        F f1 = new F();

        D d;

        // Instance method with one argument of type C.
        MethodInfo cmi1 = typeof(C).GetMethod("M1"); 
        // Instance method with no arguments.
        MethodInfo cmi2 = typeof(C).GetMethod("M2"); 
        // Static method with one argument of type C.
        MethodInfo cmi3 = typeof(C).GetMethod("M3"); 
        // Static method with two arguments of type C.
        MethodInfo cmi4 = typeof(C).GetMethod("M4"); 

        // Instance method with one argument of type C.
        MethodInfo fmi1 = typeof(F).GetMethod("M1");
        // Static method with one argument of type C.
        MethodInfo fmi3 = typeof(F).GetMethod("M3"); 
        // Static method with an argument of type F and an argument 
        // of type C.
        MethodInfo fmi4 = typeof(F).GetMethod("M4"); 

        Console.WriteLine("\nAn instance method on any type, with an argument of type C.");
        // D can represent any instance method that exactly matches its
        // signature. Methods on C and F are shown here.
        //
        d = (D) Delegate.CreateDelegate(typeof(D), c1, cmi1);
        d(c2);
        d = (D) Delegate.CreateDelegate(typeof(D), f1, fmi1);
        d(c2);

        Console.WriteLine("\nAn instance method on C with no arguments.");
        // D can represent an instance method on C that has no arguments;
        // in this case, the argument of D represents the hidden first
        // argument of any instance method. The delegate acts like a 
        // static method, and an instance of C must be passed each time
        // it is invoked.
        //
        d = (D) Delegate.CreateDelegate(typeof(D), null, cmi2);
        d(c1);

        Console.WriteLine("\nA static method on any type, with an argument of type C.");
        // D can represent any static method with the same signature.
        // Methods on F and C are shown here.
        //
        d = (D) Delegate.CreateDelegate(typeof(D), null, cmi3);
        d(c1);
        d = (D) Delegate.CreateDelegate(typeof(D), null, fmi3);
        d(c1);

        Console.WriteLine("\nA static method on any type, with an argument of");
        Console.WriteLine("    that type and an argument of type C.");
        // D can represent any static method with one argument of the
        // type the method belongs and a second argument of type C.
        // In this case, the method is closed over the instance of
        // supplied for the its first argument, and acts like an instance
        // method. Methods on F and C are shown here.
        //
        d = (D) Delegate.CreateDelegate(typeof(D), c1, cmi4);
        d(c2);
        Delegate test = 
            Delegate.CreateDelegate(typeof(D), f1, fmi4, false);

        // This final example specifies false for throwOnBindFailure 
        // in the call to CreateDelegate, so the variable 'test'
        // contains Nothing if the method fails to bind (for 
        // example, if fmi4 happened to represent a method of  
        // some class other than F).
        //
        if (test != null)
        {
            d = (D) test;
            d(c2);
        }
    }
}

/* This code example produces the following output:

An instance method on any type, with an argument of type C.
Instance method M1(C c) on C:  this.id = 42, c.ID = 1491
Instance method M1(C c) on F:  c.ID = 1491

An instance method on C with no arguments.
Instance method M2() on C:  this.id = 42

A static method on any type, with an argument of type C.
Static method M3(C c) on C:  c.ID = 42
Static method M3(C c) on F:  c.ID = 42

A static method on any type, with an argument of
    that type and an argument of type C.
Static method M4(C c1, C c2) on C:  c1.ID = 42, c2.ID = 1491
Static method M4(F f, C c) on F:  c.ID = 1491
*/
Imports System.Reflection
Imports System.Security.Permissions

' Declare a delegate type. The object of this code example
' is to show all the methods this delegate can bind to.
'
Public Delegate Sub D(ByVal c As C) 

' Declare two sample classes, C and F. Class C has an ID
' property so instances can be identified.
'
Public Class C

    Private _id As Integer

    Public ReadOnly Property ID() As Integer 
        Get
            Return _id
        End Get
    End Property

    Public Sub New(ByVal newId As Integer) 
        Me._id = newId
    End Sub
    
    Public Sub M1(ByVal c As C) 
        Console.WriteLine("Instance method M1(c As C) on C:  this.id = {0}, c.ID = {1}", _
            Me.id, c.ID)
    End Sub
    
    Public Sub M2() 
        Console.WriteLine("Instance method M2() on C:  this.id = {0}", Me.id)
    End Sub
    
    Public Shared Sub M3(ByVal c As C) 
        Console.WriteLine("Shared method M3(c As C) on C:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M4(ByVal c1 As C, ByVal c2 As C) 
        Console.WriteLine("Shared method M4(c1 As C, c2 As C) on C:  c1.ID = {0}, c2.ID = {1}", _
            c1.ID, c2.ID)
    End Sub
End Class


Public Class F
    
    Public Sub M1(ByVal c As C) 
        Console.WriteLine("Instance method M1(c As C) on F:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M3(ByVal c As C) 
        Console.WriteLine("Shared method M3(c As C) on F:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M4(ByVal f As F, ByVal c As C) 
        Console.WriteLine("Shared method M4(f As F, c As C) on F:  c.ID = {0}", c.ID)
    End Sub
End Class

Public Class Example
    
    Public Shared Sub Main() 

        Dim c1 As New C(42)
        Dim c2 As New C(1491)
        Dim f1 As New F()
        
        Dim d As D
        
        ' Instance method with one argument of type C.
        Dim cmi1 As MethodInfo = GetType(C).GetMethod("M1")
        ' Instance method with no arguments.
        Dim cmi2 As MethodInfo = GetType(C).GetMethod("M2")
        ' Shared method with one argument of type C.
        Dim cmi3 As MethodInfo = GetType(C).GetMethod("M3")
        ' Shared method with two arguments of type C.
        Dim cmi4 As MethodInfo = GetType(C).GetMethod("M4")
        
        ' Instance method with one argument of type C.
        Dim fmi1 As MethodInfo = GetType(F).GetMethod("M1")
        ' Shared method with one argument of type C.
        Dim fmi3 As MethodInfo = GetType(F).GetMethod("M3")
        ' Shared method with an argument of type F and an 
        ' argument of type C.
        Dim fmi4 As MethodInfo = GetType(F).GetMethod("M4")
        
        Console.WriteLine(vbLf & "An instance method on any type, with an argument of type C.")
        ' D can represent any instance method that exactly matches its
        ' signature. Methods on C and F are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi1), D)
        d(c2)
        d = CType([Delegate].CreateDelegate(GetType(D), f1, fmi1), D)
        d(c2)
        
        Console.WriteLine(vbLf & "An instance method on C with no arguments.")
        ' D can represent an instance method on C that has no arguments;
        ' in this case, the argument of D represents the hidden first
        ' argument of any instance method. The delegate acts like a 
        ' Shared method, and an instance of C must be passed each time
        ' it is invoked.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi2), D)
        d(c1)
        
        Console.WriteLine(vbLf & "A Shared method on any type, with an argument of type C.")
        ' D can represent any Shared method with the same signature.
        ' Methods on F and C are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi3), D)
        d(c1)
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, fmi3), D)
        d(c1)
        
        Console.WriteLine(vbLf & "A Shared method on any type, with an argument of")
        Console.WriteLine("    that type and an argument of type C.")
        ' D can represent any Shared method with one argument of the
        ' type the method belongs and a second argument of type C.
        ' In this case, the method is closed over the instance of
        ' supplied for the its first argument, and acts like an instance
        ' method. Methods on F and C are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi4), D)
        d(c2)
        Dim test As [Delegate] = _
            [Delegate].CreateDelegate(GetType(D), f1, fmi4, false)

        ' This final example specifies False for throwOnBindFailure 
        ' in the call to CreateDelegate, so the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if fmi4 happened to represent a method of  
        ' some class other than F).
        '
        If test IsNot Nothing Then
            d = CType(test, D)
            d(c2)
        End If
    
    End Sub
End Class

' This code example produces the following output:
'
'An instance method on any type, with an argument of type C.
'Instance method M1(c As C) on C:  this.id = 42, c.ID = 1491
'Instance method M1(c As C) on F:  c.ID = 1491
'
'An instance method on C with no arguments.
'Instance method M2() on C:  this.id = 42
'
'A Shared method on any type, with an argument of type C.
'Shared method M3(c As C) on C:  c.ID = 42
'Shared method M3(c As C) on F:  c.ID = 42
'
'A Shared method on any type, with an argument of
'    that type and an argument of type C.
'Shared method M4(c1 As C, c2 As C) on C:  c1.ID = 42, c2.ID = 1491
'Shared method M4(f As F, c As C) on F:  c.ID = 1491
'

Comentarios

Esta sobrecarga del método y CreateDelegate(Type, Object, MethodInfo) la sobrecarga del método, que siempre produce un error al enlazar, proporcionan la manera más flexible de crear delegados.This method overload and the CreateDelegate(Type, Object, MethodInfo) method overload, which always throws on failure to bind, provide the most flexible way to create delegates. Puede utilizarlos para crear delegados para métodos estáticos o de instancia, con o sin un primer argumento.You can use them to create delegates for either static or instance methods, with or without a first argument.

Nota

Si no proporciona un primer argumento, use la sobrecarga del CreateDelegate(Type, MethodInfo, Boolean) método para mejorar el rendimiento.If you do not supply a first argument, use the CreateDelegate(Type, MethodInfo, Boolean) method overload for better performance.

El tipo de delegado y el método deben tener tipos de valor devueltos compatibles.The delegate type and the method must have compatible return types. Es decir, el tipo de valor method devuelto de debe ser asignable al tipo de typevalor devuelto de.That is, the return type of method must be assignable to the return type of type.

Si firstArgument se proporciona, se pasa a method cada vez que se invoca el delegado; firstArgument se dice que está enlazado al delegado y se dice que el delegado está cerrado sobre su primer argumento.If firstArgument is supplied, it is passed to method every time the delegate is invoked; firstArgument is said to be bound to the delegate, and the delegate is said to be closed over its first argument. Si method es static ( method firstArgument en Visual Basic), la lista de argumentos proporcionada al invocar al delegado incluye todos los parámetros excepto el primero; si es un método de instancia, se pasa a la instancia oculta.Shared parámetro (representado por this en C#, o por Me en Visual Basic).If method is static (Shared in Visual Basic), the argument list supplied when invoking the delegate includes all parameters except the first; if method is an instance method, then firstArgument is passed to the hidden instance parameter (represented by this in C#, or by Me in Visual Basic).

Si firstArgument se proporciona, el primer parámetro de method debe ser un tipo de referencia y firstArgument debe ser compatible con ese tipo.If firstArgument is supplied, the first parameter of method must be a reference type, and firstArgument must be compatible with that type.

Importante

Si method es static ( Object enVisualBasicValueType) y sufirstArgument primer parámetro es de tipo o, puede ser un tipo de valor.SharedIf method is static (Shared in Visual Basic) and its first parameter is of type Object or ValueType, then firstArgument can be a value type. En este caso firstArgument , se aplica automáticamente la conversión boxing.In this case firstArgument is automatically boxed. La conversión boxing automática no se produce para ningún otro argumento, como lo haría C# en una llamada de función o Visual Basic.Automatic boxing does not occur for any other arguments, as it would in a C# or Visual Basic function call.

Si firstArgument es una referencia nula y method es un método de instancia, el resultado depende de las firmas del tipo type de delegado y de method:If firstArgument is a null reference and method is an instance method, the result depends on the signatures of the delegate type type and of method:

  • Si la firma de type incluye explícitamente el primer parámetro oculto methodde, se dice que el delegado representa un método de instancia abierto.If the signature of type explicitly includes the hidden first parameter of method, the delegate is said to represent an open instance method. Cuando se invoca el delegado, el primer argumento de la lista de argumentos se pasa al parámetro de instancia oculto de method.When the delegate is invoked, the first argument in the argument list is passed to the hidden instance parameter of method.

  • Si las firmas de y method type coinciden (es decir, todos los tipos de parámetro son compatibles), se dice que el delegado está cerrado en una referencia nula.If the signatures of method and type match (that is, all parameter types are compatible), then the delegate is said to be closed over a null reference. La invocación del delegado es como llamar a un método de instancia en una instancia null, lo que no es una cosa especialmente útil.Invoking the delegate is like calling an instance method on a null instance, which is not a particularly useful thing to do.

Si firstArgument es una referencia nula y method es static, el resultado depende de las firmas del tipo type de delegado y de method:If firstArgument is a null reference and method is static, the result depends on the signatures of the delegate type type and of method:

  • Si la firma de method y type coincide (es decir, todos los tipos de parámetro son compatibles), se dice que el delegado representa un método estático abierto.If the signature of method and type match (that is, all parameter types are compatible), the delegate is said to represent an open static method. Este es el caso más común de los métodos estáticos.This is the most common case for static methods. En este caso, puede obtener un rendimiento ligeramente mejor mediante la sobrecarga CreateDelegate(Type, MethodInfo, Boolean) del método.In this case, you can get slightly better performance by using the CreateDelegate(Type, MethodInfo, Boolean) method overload.

  • Si la firma de type comienza con el segundo parámetro de method y el resto de los tipos de parámetro son compatibles, se dice que el delegado está cerrado en una referencia nula.If the signature of type begins with the second parameter of method and the rest of the parameter types are compatible, then the delegate is said to be closed over a null reference. Cuando se invoca el delegado, se pasa una referencia nula al primer parámetro de method.When the delegate is invoked, a null reference is passed to the first parameter of method.

Nota

A partir de ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess , este método se puede usar para tener acceso a métodos no públicos si el llamador se ha concedido con la marca y si el conjunto de permisos de los métodos no públicos está restringido al conjunto de permisos del llamador o a un .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1subconjunto. mismo.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public methods if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public methods is restricted to the caller's grant set, or a subset thereof. (Consulte consideraciones de seguridad para la reflexión).(See Security Considerations for Reflection.)

Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Tipos de parámetro y tipo de valor devuelto compatiblesCompatible Parameter Types and Return Type

Los tipos de parámetro y el tipo de valor devuelto de un delegado deben ser compatibles con los tipos de parámetro y el tipo de valor devuelto del método que representa el delegado. no es necesario que los tipos coincidan exactamente.The parameter types and return type of a delegate must be compatible with the parameter types and return type of the method the delegate represents; the types do not have to match exactly.

Nota

En la .NET Framework versión 1,0 y 1,1, los tipos deben coincidir exactamente.In the .NET Framework version 1.0 and 1.1 the types must match exactly.

Un parámetro de un delegado es compatible con el parámetro correspondiente de un método si el tipo del parámetro del delegado es más restrictivo que el del método, porque así se garantiza que el argumento que se pase al delegado también se podrá pasar de forma segura al método.A parameter of a delegate is compatible with the corresponding parameter of a method if the type of the delegate parameter is more restrictive than the type of the method parameter, because this guarantees that an argument passed to the delegate can be passed safely to the method.

De forma similar, el tipo de valor devuelto de un delegado es compatible con el tipo de valor devuelto de un método si el del método es más restrictivo que el del delegado, porque así se garantiza que el tipo de valor devuelto por el método se puede convertir con seguridad al tipo de valor devuelto del delegado.Similarly, the return type of a delegate is compatible with the return type of a method if the return type of the method is more restrictive than the return type of the delegate, because this guarantees that the return value of the method can be cast safely to the return type of the delegate.

Por ejemplo, un delegado con un parámetro de tipo Hashtable y un tipo de Object valor devuelto puede representar un método con un parámetro Object de tipo y un valor devuelto de tipo Hashtable.For example, a delegate with a parameter of type Hashtable and a return type of Object can represent a method with a parameter of type Object and a return value of type Hashtable.

Determinar los métodos que un delegado puede representarDetermining the Methods a Delegate Can Represent

Otra manera útil de pensar en la flexibilidad proporcionada por esta sobrecarga de CreateDelegate es que cualquier delegado determinado puede representar cuatro combinaciones diferentes de la firma de método y el tipo de método (estático frente a instancia).Another useful way to think of the flexibility provided by this overload of CreateDelegate is that any given delegate can represent four different combinations of method signature and method kind (static versus instance). Considere la posibilidad de D usar un tipo de delegado Ccon un argumento de tipo.Consider a delegate type D with one argument of type C. A continuación se describen los D métodos que pueden representar y omitir el tipo de valor devuelto, ya que debe coincidir en todos los casos:The following describes the methods D can represent, ignoring the return type since it must match in all cases:

  • Dpuede representar cualquier método de instancia que tenga exactamente un argumento de Ctipo, independientemente del tipo al que pertenezca el método de instancia.D can represent any instance method that has exactly one argument of type C, regardless of what type the instance method belongs to. Cuando CreateDelegate se llama a firstArgument , es una instancia del tipo method al que pertenece y se dice que el delegado resultante está cerrado en esa instancia.When CreateDelegate is called, firstArgument is an instance of the type method belongs to, and the resulting delegate is said to be closed over that instance. (Trivialmente, D también se puede cerrar en una referencia nula si firstArgument es null).(Trivially, D can also be closed over a null reference if firstArgument is null.)

  • Dpuede representar un método de instancia C de que no tiene ningún argumento.D can represent an instance method of C that has no arguments. Cuando CreateDelegate se llama a firstArgument , es una referencia nula.When CreateDelegate is called, firstArgument is a null reference. El delegado resultante representa un método de instancia abierto y se debe proporcionar C una instancia de cada vez que se invoca.The resulting delegate represents an open instance method, and an instance of C must be supplied each time it is invoked.

  • Dpuede representar un método estático que toma un argumento de tipo Cy ese método puede pertenecer a cualquier tipo.D can represent a static method that takes one argument of type C, and that method can belong to any type. Cuando CreateDelegate se llama a firstArgument , es una referencia nula.When CreateDelegate is called, firstArgument is a null reference. El delegado resultante representa un método estático abierto y se debe proporcionar una C instancia de cada vez que se invoca.The resulting delegate represents an open static method, and an instance of C must be supplied each time it is invoked.

  • Dpuede representar un método estático que pertenece al tipo F y tiene dos argumentos, de tipo F y tipo C.D can represent a static method that belongs to type F and has two arguments, of type F and type C. Cuando CreateDelegate se llama a firstArgument , es una instancia Fde.When CreateDelegate is called, firstArgument is an instance of F. El delegado resultante representa un método estático que se cierra en esa instancia de F.The resulting delegate represents a static method that is closed over that instance of F. Tenga en cuenta que en el F caso C de que y sean del mismo tipo, el método estático tiene dos argumentos de ese tipo.Note that in the case where F and C are the same type, the static method has two arguments of that type. (En este caso, D se cierra en una referencia nula si firstArgument es null).(In this case, D is closed over a null reference if firstArgument is null.)

Seguridad

ReflectionPermission
Cuando se invoca enlazado en tiempo de ejecución mediante InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])mecanismos como.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Consulte también:

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

Crea un delegado del tipo especificado que representa el método de instancia determinado que se va a invocar en la instancia de clase especificada, con la distinción de mayúsculas y minúsculas y el comportamiento que se hayan concretado para cuando se produce un error al enlazar.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.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ target, System::String ^ method, bool ignoreCase, bool throwOnBindFailure);
public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure);
static member CreateDelegate : Type * obj * string * bool * bool -> Delegate

Parámetros

type
Type

Type de delegado que se va a crear.The Type of delegate to create.

target
Object

Instancia de clase en la que se invoca a method.The class instance on which method is invoked.

method
String

Nombre del método de instancia que el delegado va a representar.The name of the instance method that the delegate is to represent.

ignoreCase
Boolean

Valor booleano que indica si debe omitirse la distinción de mayúsculas y minúsculas al comparar el nombre del método.A Boolean indicating whether to ignore the case when comparing the name of the method.

throwOnBindFailure
Boolean

Es true para iniciar una excepción si no se puede enlazar method; en caso contrario, es false.true to throw an exception if method cannot be bound; otherwise, false.

Devoluciones

Delegado del tipo especificado que representa el método de instancia especificado que se va a invocar en la instancia de clase especificada.A delegate of the specified type that represents the specified instance method to invoke on the specified class instance.

Excepciones

type es null.type is null.

O bien-or- target es null.target is null.

o bien-or- method es null.method is null.

type no hereda MulticastDelegate.type does not inherit MulticastDelegate.

o bien-or- type no es un RuntimeType.type is not a RuntimeType. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

o bien-or- method no es un método de instancia.method is not an instance method.

o bien-or- method no se puede enlazar (por ejemplo, porque no se encuentra) y throwOnBindFailure es true.method cannot be bound, for example because it cannot be found, and throwOnBindFailure is true.

No se encuentra el método Invoke de type.The Invoke method of type is not found.

El autor de la llamada no tiene los permisos necesarios para acceder a method.The caller does not have the permissions necessary to access method.

Comentarios

Este método solo crea los delegados para los métodos de instancia.This method creates delegates for instance methods only. Un método de instancia es un método que está asociado a una instancia de una clase; un método estático es un método que está asociado a la propia clase.An instance method is a method that is associated with an instance of a class; a static method is a method that is associated with the class itself.

Nota

A partir de ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess , este método se puede usar para tener acceso a métodos no públicos si el llamador se ha concedido con la marca y si el conjunto de permisos de los métodos no públicos está restringido al conjunto de permisos del llamador o a un .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1subconjunto. mismo.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public methods if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public methods is restricted to the caller's grant set, or a subset thereof. (Consulte consideraciones de seguridad para la reflexión).(See Security Considerations for Reflection.)

Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Seguridad

ReflectionPermission
Cuando se invoca enlazado en tiempo de ejecución mediante InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])mecanismos como.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Consulte también:

CreateDelegate(Type, MethodInfo, Boolean)

Crea un delegado del tipo especificado para representar el método estático especificado, con el comportamiento establecido para el caso de que se produzca un error al enlazar.Creates a delegate of the specified type to represent the specified static method, with the specified behavior on failure to bind.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Reflection::MethodInfo ^ method, bool throwOnBindFailure);
public static Delegate CreateDelegate (Type type, System.Reflection.MethodInfo method, bool throwOnBindFailure);
static member CreateDelegate : Type * System.Reflection.MethodInfo * bool -> Delegate

Parámetros

type
Type

Type de delegado que se va a crear.The Type of delegate to create.

method
MethodInfo

MethodInfo que describe el método estático o de instancia que va a representar el delegado.The MethodInfo describing the static or instance method the delegate is to represent.

throwOnBindFailure
Boolean

Es true para iniciar una excepción si no se puede enlazar method; en caso contrario, es false.true to throw an exception if method cannot be bound; otherwise, false.

Devoluciones

Delegado del tipo especificado para representar el método estático especificado.A delegate of the specified type to represent the specified static method.

Excepciones

type es null.type is null.

o bien-or- method es null.method is null.

type no hereda MulticastDelegate.type does not inherit MulticastDelegate.

O bien-or- type no es un RuntimeType.type is not a RuntimeType. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

O bien-or- No se puede enlazar method y throwOnBindFailure es true.method cannot be bound, and throwOnBindFailure is true.

o bien-or- method no es un RuntimeMethodInfo.method is not a RuntimeMethodInfo. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

No se encuentra el método Invoke de type.The Invoke method of type is not found.

El autor de la llamada no tiene los permisos necesarios para acceder a method.The caller does not have the permissions necessary to access method.

Ejemplos

Esta sección contiene dos ejemplos de código.This section contains two code examples. En el primer ejemplo se muestran los dos tipos de delegados que se pueden crear con esta sobrecarga del método: abrir sobre un método de instancia y abrir sobre un método estático.The first example demonstrates the two kinds of delegates that can be created with this method overload: open over an instance method and open over a static method.

En el segundo ejemplo de código se muestran los tipos de parámetros compatibles y los tipos de valor devueltos.The second code example demonstrates compatible parameter types and return types.

Ejemplo 1Example 1

En el ejemplo de código siguiente se muestran las dos maneras en que se puede crear un delegado CreateDelegate mediante esta sobrecarga del método.The following code example demonstrates the two ways a delegate can be created using this overload of the CreateDelegate method.

Nota

Hay dos sobrecargas del CreateDelegate método que especifican un MethodInfo , pero no un primer argumento; su funcionalidad es la misma, salvo que se puede especificar si se va a producir un error al enlazar, y el otro siempre produce una excepción.There are two overloads of the CreateDelegate method that specify a MethodInfo but not a first argument; their functionality is the same except that one allows you to specify whether to throw on failure to bind, and the other always throws. En este ejemplo de código se usan las dos sobrecargas.This code example uses both overloads.

En el ejemplo se declara una C clase con un método M2 estático y un método M1de instancia, y dos tipos D1 de delegado: toma C una instancia de y una D2 cadena y toma una cadena.The example declares a class C with a static method M2 and an instance method M1, and two delegate types: D1 takes an instance of C and a string, and D2 takes a string.

Una segunda clase denominada Example contiene el código que crea los delegados.A second class named Example contains the code that creates the delegates.

  • Se crea un delegado D1de tipo, que representa un método de instancia abierto, para el M1método de instancia.A delegate of type D1, representing an open instance method, is created for the instance method M1. Se debe pasar una instancia de cuando se invoca el delegado.An instance must be passed when the delegate is invoked.

  • Se crea un delegado D2de tipo que representa un método estático abierto para el método M2estático.A delegate of type D2, representing an open static method, is created for the static method M2.

using System;
using System.Reflection;
using System.Security.Permissions;

// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();

// A sample class with an instance method and a static method.
//
public class C
{
    private int id;
    public C(int id) { this.id = id; }

    public void M1(string s) 
    { 
        Console.WriteLine("Instance method M1 on C:  id = {0}, s = {1}",
            this.id, s);
    }
  
    public static void M2(string s)
    { 
        Console.WriteLine("Static method M2 on C:  s = {0}", s); 
    }
}

public class Example
{
    public static void Main()
    {
        C c1 = new C(42);

        // Get a MethodInfo for each method.
        //
        MethodInfo mi1 = typeof(C).GetMethod("M1", 
            BindingFlags.Public | BindingFlags.Instance);
        MethodInfo mi2 = typeof(C).GetMethod("M2",
            BindingFlags.Public | BindingFlags.Static);

        D1 d1;
        D2 d2;
        D3 d3;


        Console.WriteLine("\nAn instance method closed over C.");
        // In this case, the delegate and the
        // method must have the same list of argument types; use
        // delegate type D2 with instance method M1.
        //
        Delegate test = 
            Delegate.CreateDelegate(typeof(D2), c1, mi1, false);

        // Because false was specified for throwOnBindFailure 
        // in the call to CreateDelegate, the variable 'test'
        // contains null if the method fails to bind (for 
        // example, if mi1 happened to represent a method of  
        // some class other than C).
        //
        if (test != null)
        {
            d2 = (D2) test;

            // The same instance of C is used every time the 
            // delegate is invoked.
            d2("Hello, World!");
            d2("Hi, Mom!");
        }


        Console.WriteLine("\nAn open instance method.");
        // In this case, the delegate has one more 
        // argument than the instance method; this argument comes
        // at the beginning, and represents the hidden instance
        // argument of the instance method. Use delegate type D1
        // with instance method M1.
        //
        d1 = (D1) Delegate.CreateDelegate(typeof(D1), null, mi1);

        // An instance of C must be passed in each time the 
        // delegate is invoked.
        //
        d1(c1, "Hello, World!");
        d1(new C(5280), "Hi, Mom!");


        Console.WriteLine("\nAn open static method.");
        // In this case, the delegate and the method must 
        // have the same list of argument types; use delegate type
        // D2 with static method M2.
        //
        d2 = (D2) Delegate.CreateDelegate(typeof(D2), null, mi2);

        // No instances of C are involved, because this is a static
        // method. 
        //
        d2("Hello, World!");
        d2("Hi, Mom!");


        Console.WriteLine("\nA static method closed over the first argument (String).");
        // The delegate must omit the first argument of the method.
        // A string is passed as the firstArgument parameter, and 
        // the delegate is bound to this string. Use delegate type 
        // D3 with static method M2. 
        //
        d3 = (D3) Delegate.CreateDelegate(typeof(D3), 
            "Hello, World!", mi2);

        // Each time the delegate is invoked, the same string is
        // used.
        d3();
    }
}

/* This code example produces the following output:

An instance method closed over C.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 42, s = Hi, Mom!

An open instance method.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 5280, s = Hi, Mom!

An open static method.
Static method M2 on C:  s = Hello, World!
Static method M2 on C:  s = Hi, Mom!

A static method closed over the first argument (String).
Static method M2 on C:  s = Hello, World!
 */
Imports System.Reflection
Imports System.Security.Permissions

' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C, ByVal s As String) 
Public Delegate Sub D2(ByVal s As String) 
Public Delegate Sub D3() 

' A sample class with an instance method and a Shared method.
'
Public Class C
    Private id As Integer
    Public Sub New(ByVal id As Integer) 
        Me.id = id
    End Sub

    Public Sub M1(ByVal s As String) 
        Console.WriteLine("Instance method M1 on C:  id = {0}, s = {1}", _
            Me.id, s)
    End Sub
    
    Public Shared Sub M2(ByVal s As String) 
        Console.WriteLine("Shared method M2 on C:  s = {0}", s)
    End Sub
End Class

Public Class Example
    
    Public Shared Sub Main() 

        Dim c1 As New C(42)
        
        ' Get a MethodInfo for each method.
        '
        Dim mi1 As MethodInfo = GetType(C).GetMethod("M1", _
            BindingFlags.Public Or BindingFlags.Instance)
        Dim mi2 As MethodInfo = GetType(C).GetMethod("M2", _
            BindingFlags.Public Or BindingFlags.Static)
        
        Dim d1 As D1
        Dim d2 As D2
        Dim d3 As D3
        
        
        Console.WriteLine(vbLf & "An instance method closed over C.")
        ' In this case, the delegate and the
        ' method must have the same list of argument types; use
        ' delegate type D2 with instance method M1.
        '
        Dim test As [Delegate] = _
            [Delegate].CreateDelegate(GetType(D2), c1, mi1, False)

        ' Because False was specified for throwOnBindFailure 
        ' in the call to CreateDelegate, the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if mi1 happened to represent a method of 
        ' some class other than C).
        '
        If test IsNot Nothing Then
            d2 = CType(test, D2)

            ' The same instance of C is used every time the
            ' delegate is invoked.
            d2("Hello, World!")
            d2("Hi, Mom!")
        End If
        
        
        Console.WriteLine(vbLf & "An open instance method.")
        ' In this case, the delegate has one more 
        ' argument than the instance method; this argument comes
        ' at the beginning, and represents the hidden instance
        ' argument of the instance method. Use delegate type D1
        ' with instance method M1.
        '
        d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)
        
        ' An instance of C must be passed in each time the 
        ' delegate is invoked.
        '
        d1(c1, "Hello, World!")
        d1(New C(5280), "Hi, Mom!")
        
        
        Console.WriteLine(vbLf & "An open Shared method.")
        ' In this case, the delegate and the method must 
        ' have the same list of argument types; use delegate type
        ' D2 with Shared method M2.
        '
        d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)
        
        ' No instances of C are involved, because this is a Shared
        ' method. 
        '
        d2("Hello, World!")
        d2("Hi, Mom!")
        
        
        Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
        ' The delegate must omit the first argument of the method.
        ' A string is passed as the firstArgument parameter, and 
        ' the delegate is bound to this string. Use delegate type 
        ' D3 with Shared method M2. 
        '
        d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)
        
        ' Each time the delegate is invoked, the same string is
        ' used.
        d3()
    
    End Sub
End Class

' This code example produces the following output:
'
'An instance method closed over C.
'Instance method M1 on C:  id = 42, s = Hello, World!
'Instance method M1 on C:  id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C:  id = 42, s = Hello, World!
'Instance method M1 on C:  id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C:  s = Hello, World!
'Shared method M2 on C:  s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C:  s = Hello, World!
' 

Ejemplo 2Example 2

En el ejemplo de código siguiente se muestra la compatibilidad de los tipos de parámetro y los tipos de valor devuelto.The following code example demonstrates compatibility of parameter types and return types.

Nota

En este ejemplo de código CreateDelegate(Type, MethodInfo) se usa la sobrecarga del método.This code example uses the CreateDelegate(Type, MethodInfo) method overload. El uso de otras sobrecargas que toman MethodInfo es similar.The use of other overloads that take MethodInfo is similar.

En el ejemplo de código se define una Base clase base denominada y Derived una clase denominada que Basese deriva de.The code example defines a base class named Base and a class named Derived that derives from Base. La clase derivada tiene un static métodoShared (en Visual Basic) denominado MyMethod con un parámetro de tipo Base y un tipo de valor Deriveddevuelto de.The derived class has a static (Shared in Visual Basic) method named MyMethod with one parameter of type Base and a return type of Derived. En el ejemplo de código también se define Example un delegado denominado que tiene un Derived parámetro de tipo y un Basetipo de valor devuelto de.The code example also defines a delegate named Example that has one parameter of type Derived and a return type of Base.

En el ejemplo de código se muestra que Example el delegado denominado se puede usar para MyMethodrepresentar el método.The code example demonstrates that the delegate named Example can be used to represent the method MyMethod. El método se puede enlazar al delegado porque:The method can be bound to the delegate because:

  • El tipo de parámetro del delegado (Derived) es más restrictivo que el tipo de parámetro de MyMethod (Base), de modo que siempre es seguro pasar el argumento del delegado a MyMethod.The parameter type of the delegate (Derived) is more restrictive than the parameter type of MyMethod (Base), so that it is always safe to pass the argument of the delegate to MyMethod.

  • El tipo de valor MyMethod devuelto de (Derived) es más restrictivo que el tipo de parámetro delBasedelegado (), de modo que siempre es seguro convertir el tipo de valor devuelto del método al tipo de valor devuelto del delegado.The return type of MyMethod (Derived) is more restrictive than the parameter type of the delegate (Base), so that it is always safe to cast the return type of the method to the return type of the delegate.

El ejemplo de código no genera ningún resultado.The code example produces no output.

using namespace System;
using namespace System::Reflection;

// Define two classes to use in the demonstration, a base class and 
// a class that derives from it.
//
public ref class Base {};

public ref class Derived : Base
{
    // Define a static method to use in the demonstration. The method 
    // takes an instance of Base and returns an instance of Derived.  
    // For the purposes of the demonstration, it is not necessary for 
    // the method to do anything useful. 
    //
public:
    static Derived^ MyMethod(Base^ arg)
    {
        Base^ dummy = arg;
        return gcnew Derived();
    }
};

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base^ Example(Derived^ arg);

void main()
{
    // The binding flags needed to retrieve MyMethod.
    BindingFlags flags = BindingFlags::Public | BindingFlags::Static;

    // Get a MethodInfo that represents MyMethod.
    MethodInfo^ minfo = Derived::typeid->GetMethod("MyMethod", flags);

    // Demonstrate contravariance of parameter types and covariance
    // of return types by using the delegate Example to represent
    // MyMethod. The delegate binds to the method because the
    // parameter of the delegate is more restrictive than the 
    // parameter of the method (that is, the delegate accepts an
    // instance of Derived, which can always be safely passed to
    // a parameter of type Base), and the return type of MyMethod
    // is more restrictive than the return type of Example (that
    // is, the method returns an instance of Derived, which can
    // always be safely cast to type Base). 
    //
    Example^ ex = 
        (Example^) Delegate::CreateDelegate(Example::typeid, minfo);

    // Execute MyMethod using the delegate Example.
    //        
    Base^ b = ex(gcnew Derived());
}
using System;
using System.Reflection;

// Define two classes to use in the demonstration, a base class and 
// a class that derives from it.
//
public class Base {}

public class Derived : Base
{
    // Define a static method to use in the demonstration. The method 
    // takes an instance of Base and returns an instance of Derived.  
    // For the purposes of the demonstration, it is not necessary for 
    // the method to do anything useful. 
    //
    public static Derived MyMethod(Base arg)
    {
        Base dummy = arg;
        return new Derived();
    }
}

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example(Derived arg);

class Test
{
    public static void Main()
    {
        // The binding flags needed to retrieve MyMethod.
        BindingFlags flags = BindingFlags.Public | BindingFlags.Static;

        // Get a MethodInfo that represents MyMethod.
        MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);

        // Demonstrate contravariance of parameter types and covariance
        // of return types by using the delegate Example to represent
        // MyMethod. The delegate binds to the method because the
        // parameter of the delegate is more restrictive than the 
        // parameter of the method (that is, the delegate accepts an
        // instance of Derived, which can always be safely passed to
        // a parameter of type Base), and the return type of MyMethod
        // is more restrictive than the return type of Example (that
        // is, the method returns an instance of Derived, which can
        // always be safely cast to type Base). 
        //
        Example ex = 
            (Example) Delegate.CreateDelegate(typeof(Example), minfo);

        // Execute MyMethod using the delegate Example.
        //        
        Base b = ex(new Derived());
    }
}
Imports System.Reflection

' Define two classes to use in the demonstration, a base class and 
' a class that derives from it.
'
Public Class Base
End Class

Public Class Derived
    Inherits Base

    ' Define a Shared method to use in the demonstration. The method 
    ' takes an instance of Base and returns an instance of Derived.  
    ' For the purposes of the demonstration, it is not necessary for 
    ' the method to do anything useful. 
    '
    Public Shared Function MyMethod(ByVal arg As Base) As Derived
        Dim dummy As Base = arg
        Return New Derived()
    End Function

End Class

' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base

Module Test

    Sub Main()

        ' The binding flags needed to retrieve MyMethod.
        Dim flags As BindingFlags = _
            BindingFlags.Public Or BindingFlags.Static

        ' Get a MethodInfo that represents MyMethod.
        Dim minfo As MethodInfo = _
            GetType(Derived).GetMethod("MyMethod", flags)

        ' Demonstrate contravariance of parameter types and covariance
        ' of return types by using the delegate Example to represent
        ' MyMethod. The delegate binds to the method because the
        ' parameter of the delegate is more restrictive than the 
        ' parameter of the method (that is, the delegate accepts an
        ' instance of Derived, which can always be safely passed to
        ' a parameter of type Base), and the return type of MyMethod
        ' is more restrictive than the return type of Example (that
        ' is, the method returns an instance of Derived, which can
        ' always be safely cast to type Base). 
        '
        Dim ex As Example = CType( _
            [Delegate].CreateDelegate(GetType(Example), minfo), _
            Example _
        )

        ' Execute MyMethod using the delegate Example.
        '        
        Dim b As Base = ex(New Derived())
    End Sub
End Module

Comentarios

Esta sobrecarga del método puede crear delegados de método estático abierto y delegados de método de instancia abierta, es decir, delegados que exponen el primer argumento oculto de los métodos de instancia.This method overload can create open static method delegates and open instance method delegates - that is, delegates that expose the hidden first argument of instance methods. Para obtener una explicación detallada, vea la sobrecarga CreateDelegate(Type, Object, MethodInfo, Boolean) de método más general, que permite crear todas las combinaciones de los delegados abiertos o cerrados para los métodos estáticos o de instancia.For a detailed explanation, see the more general CreateDelegate(Type, Object, MethodInfo, Boolean) method overload, which allows you to create all combinations of open or closed delegates for instance or static methods.

Nota

Esta sobrecarga del método se debe utilizar cuando el delegado no está cerrado sobre su primer argumento, porque es algo más rápido en ese caso.This method overload should be used when the delegate is not closed over its first argument, because it is somewhat faster in that case.

Nota

A partir de ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess , este método se puede usar para tener acceso a métodos no públicos si el llamador se ha concedido con la marca y si el conjunto de permisos de los métodos no públicos está restringido al conjunto de permisos del llamador o a un .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1subconjunto. mismo.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public methods if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public methods is restricted to the caller's grant set, or a subset thereof. (Consulte consideraciones de seguridad para la reflexión).(See Security Considerations for Reflection.)

Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Tipos de parámetro y tipo de valor devuelto compatiblesCompatible Parameter Types and Return Type

Los tipos de parámetro y el tipo de valor devuelto de un delegado deben ser compatibles con los tipos de parámetro y el tipo de valor devuelto del método que representa el delegado. no es necesario que los tipos coincidan exactamente.The parameter types and return type of a delegate must be compatible with the parameter types and return type of the method the delegate represents; the types do not have to match exactly.

Nota

En la .NET Framework versión 1,0 y 1,1, los tipos deben coincidir exactamente.In the .NET Framework version 1.0 and 1.1, the types must match exactly.

Un parámetro de un delegado es compatible con el parámetro correspondiente de un método si el tipo del parámetro del delegado es más restrictivo que el del método, porque así se garantiza que el argumento que se pase al delegado también se podrá pasar de forma segura al método.A parameter of a delegate is compatible with the corresponding parameter of a method if the type of the delegate parameter is more restrictive than the type of the method parameter, because this guarantees that an argument passed to the delegate can be passed safely to the method.

De forma similar, el tipo de valor devuelto de un delegado es compatible con el tipo de valor devuelto de un método si el del método es más restrictivo que el del delegado, porque así se garantiza que el tipo de valor devuelto por el método se puede convertir con seguridad al tipo de valor devuelto del delegado.Similarly, the return type of a delegate is compatible with the return type of a method if the return type of the method is more restrictive than the return type of the delegate, because this guarantees that the return value of the method can be cast safely to the return type of the delegate.

Por ejemplo, un delegado con un parámetro de tipo Hashtable y un tipo de Object valor devuelto puede representar un método con un parámetro Object de tipo y un valor devuelto de tipo Hashtable.For example, a delegate with a parameter of type Hashtable and a return type of Object can represent a method with a parameter of type Object and a return value of type Hashtable.

Seguridad

ReflectionPermission
Cuando se invoca enlazado en tiempo de ejecución mediante InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])mecanismos como.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Consulte también:

CreateDelegate(Type, Object, String)

Crea un delegado del tipo especificado que representa el método de instancia especificado que se va a invocar en la instancia de clase especificada.Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ target, System::String ^ method);
public static Delegate CreateDelegate (Type type, object target, string method);
static member CreateDelegate : Type * obj * string -> Delegate

Parámetros

type
Type

Type de delegado que se va a crear.The Type of delegate to create.

target
Object

Instancia de clase en la que se invoca a method.The class instance on which method is invoked.

method
String

Nombre del método de instancia que el delegado va a representar.The name of the instance method that the delegate is to represent.

Devoluciones

Delegado del tipo especificado que representa el método de instancia especificado que se va a invocar en la instancia de clase especificada.A delegate of the specified type that represents the specified instance method to invoke on the specified class instance.

Excepciones

type es null.type is null.

o bien-or- target es null.target is null.

o bien-or- method es null.method is null.

type no hereda MulticastDelegate.type does not inherit MulticastDelegate.

O bien-or- type no es un RuntimeType.type is not a RuntimeType. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

o bien-or- method no es un método de instancia.method is not an instance method.

O bien-or- method no se puede enlazar, por ejemplo, porque no se encuentra.method cannot be bound, for example because it cannot be found.

No se encuentra el método Invoke de type.The Invoke method of type is not found.

El autor de la llamada no tiene los permisos necesarios para acceder a method.The caller does not have the permissions necessary to access method.

Comentarios

Este método solo crea los delegados para los métodos de instancia.This method creates delegates for instance methods only. Un método de instancia es un método que está asociado a una instancia de una clase; un método estático es un método que está asociado a la propia clase.An instance method is a method that is associated with an instance of a class; a static method is a method that is associated with the class itself.

Esta sobrecarga del método es equivalente a llamar CreateDelegate(Type, Object, String, Boolean, Boolean) a la sobrecarga del método false , ignoreCase especificando throwOnBindFailurepara y true para.This method overload is equivalent to calling the CreateDelegate(Type, Object, String, Boolean, Boolean) method overload, specifying false for ignoreCase and true for throwOnBindFailure.

Nota

A partir de ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess , este método se puede usar para tener acceso a métodos no públicos si el llamador se ha concedido con la marca y si el conjunto de permisos de los métodos no públicos está restringido al conjunto de permisos del llamador o a un .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1subconjunto. mismo.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public methods if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public methods is restricted to the caller's grant set, or a subset thereof. (Consulte consideraciones de seguridad para la reflexión).(See Security Considerations for Reflection.)

Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Seguridad

ReflectionPermission
Cuando se invoca enlazado en tiempo de ejecución mediante InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])mecanismos como.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Consulte también:

CreateDelegate(Type, Object, MethodInfo)

Crea un delegado del tipo especificado que representa el método estático o de instancia especificado, con el primer argumento definido.Creates a delegate of the specified type that represents the specified static or instance method, with the specified first argument.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ firstArgument, System::Reflection::MethodInfo ^ method);
public static Delegate CreateDelegate (Type type, object firstArgument, System.Reflection.MethodInfo method);
static member CreateDelegate : Type * obj * System.Reflection.MethodInfo -> Delegate

Parámetros

type
Type

Type de delegado que se va a crear.The Type of delegate to create.

firstArgument
Object

Objeto al que se enlaza el delegado o null para tratar method como static (Shared en Visual Basic).The object to which the delegate is bound, or null to treat method as static (Shared in Visual Basic).

method
MethodInfo

MethodInfo que describe el método estático o de instancia que va a representar el delegado.The MethodInfo describing the static or instance method the delegate is to represent.

Devoluciones

Delegado del tipo especificado para representar el método estático o de instancia definido.A delegate of the specified type that represents the specified static or instance method.

Excepciones

type es null.type is null.

O bien-or- method es null.method is null.

type no hereda MulticastDelegate.type does not inherit MulticastDelegate.

O bien-or- type no es un RuntimeType.type is not a RuntimeType. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

O bien-or- No se puede enlazar method.method cannot be bound.

o bien-or- method no es un RuntimeMethodInfo.method is not a RuntimeMethodInfo. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

No se encuentra el método Invoke de type.The Invoke method of type is not found.

El autor de la llamada no tiene los permisos necesarios para acceder a method.The caller does not have the permissions necessary to access method.

Ejemplos

Esta sección contiene tres ejemplos de código.This section contains three code examples. En el primer ejemplo se muestran los cuatro tipos de delegados que se pueden crear: cerrados en un método de instancia, abrir sobre un método de instancia, abrir sobre un método estático y cerrar en un método estático.The first example demonstrates the four kinds of delegates that can be created: closed over an instance method, open over an instance method, open over a static method, and closed over a static method.

En el segundo ejemplo de código se muestran los tipos de parámetros compatibles y los tipos de valor devueltos.The second code example demonstrates compatible parameter types and return types.

En el tercer ejemplo de código se define un tipo de delegado único y se muestran todos los métodos que el tipo de delegado puede representar.The third code example defines a single delegate type, and shows all the methods that delegate type can represent.

Ejemplo 1Example 1

En el ejemplo de código siguiente se muestran las cuatro maneras en que se puede crear un delegado CreateDelegate mediante esta sobrecarga del método.The following code example demonstrates the four ways a delegate can be created using this overload of the CreateDelegate method.

Nota

Hay dos sobrecargas del CreateDelegate método que especifican firstArgument y MethodInfo, su funcionalidad es la misma, salvo que una permite especificar si se va a producir un error al enlazar y la otra siempre produce una excepción.There are two overloads of the CreateDelegate method that specify firstArgument and a MethodInfo; their functionality is the same except that one allows you to specify whether to throw on failure to bind, and the other always throws. En este ejemplo de código se usan las dos sobrecargas.This code example uses both overloads.

En el ejemplo se declara una C clase con un método M2 estático y un método M1de instancia, y tres tipos D1 de delegado: toma C una instancia de y D2 una cadena, toma una cadena y D3no tiene argumentos.The example declares a class C with a static method M2 and an instance method M1, and three delegate types: D1 takes an instance of C and a string, D2 takes a string, and D3 has no arguments.

Una segunda clase denominada Example contiene el código que crea los delegados.A second class named Example contains the code that creates the delegates.

  • Se crea un delegado D2de tipo, cerrado en una Cinstancia de, para el método M1de instancia.A delegate of type D2, closed over an instance of C, is created for the instance method M1. Se invoca con cadenas diferentes para mostrar que siempre se usa la instancia enlazada C de.It is invoked with different strings, to show that the bound instance of C is always used.

  • Se crea un delegado D1de tipo, que representa un método de instancia abierto, para el M1método de instancia.A delegate of type D1, representing an open instance method, is created for the instance method M1. Se debe pasar una instancia de cuando se invoca el delegado.An instance must be passed when the delegate is invoked.

  • Se crea un delegado D2de tipo que representa un método estático abierto para el método M2estático.A delegate of type D2, representing an open static method, is created for the static method M2.

  • Por último, se crea un D3delegado de tipo, cerrado en una cadena, para el método M2estático.Finally, a delegate of type D3, closed over a string, is created for the static method M2. El método se invoca para mostrar que usa la cadena enlazada.The method is invoked to show that it uses the bound string.

using System;
using System.Reflection;
using System.Security.Permissions;

// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();

// A sample class with an instance method and a static method.
//
public class C
{
    private int id;
    public C(int id) { this.id = id; }

    public void M1(string s) 
    { 
        Console.WriteLine("Instance method M1 on C:  id = {0}, s = {1}",
            this.id, s);
    }
  
    public static void M2(string s)
    { 
        Console.WriteLine("Static method M2 on C:  s = {0}", s); 
    }
}

public class Example
{
    public static void Main()
    {
        C c1 = new C(42);

        // Get a MethodInfo for each method.
        //
        MethodInfo mi1 = typeof(C).GetMethod("M1", 
            BindingFlags.Public | BindingFlags.Instance);
        MethodInfo mi2 = typeof(C).GetMethod("M2",
            BindingFlags.Public | BindingFlags.Static);

        D1 d1;
        D2 d2;
        D3 d3;


        Console.WriteLine("\nAn instance method closed over C.");
        // In this case, the delegate and the
        // method must have the same list of argument types; use
        // delegate type D2 with instance method M1.
        //
        Delegate test = 
            Delegate.CreateDelegate(typeof(D2), c1, mi1, false);

        // Because false was specified for throwOnBindFailure 
        // in the call to CreateDelegate, the variable 'test'
        // contains null if the method fails to bind (for 
        // example, if mi1 happened to represent a method of  
        // some class other than C).
        //
        if (test != null)
        {
            d2 = (D2) test;

            // The same instance of C is used every time the 
            // delegate is invoked.
            d2("Hello, World!");
            d2("Hi, Mom!");
        }


        Console.WriteLine("\nAn open instance method.");
        // In this case, the delegate has one more 
        // argument than the instance method; this argument comes
        // at the beginning, and represents the hidden instance
        // argument of the instance method. Use delegate type D1
        // with instance method M1.
        //
        d1 = (D1) Delegate.CreateDelegate(typeof(D1), null, mi1);

        // An instance of C must be passed in each time the 
        // delegate is invoked.
        //
        d1(c1, "Hello, World!");
        d1(new C(5280), "Hi, Mom!");


        Console.WriteLine("\nAn open static method.");
        // In this case, the delegate and the method must 
        // have the same list of argument types; use delegate type
        // D2 with static method M2.
        //
        d2 = (D2) Delegate.CreateDelegate(typeof(D2), null, mi2);

        // No instances of C are involved, because this is a static
        // method. 
        //
        d2("Hello, World!");
        d2("Hi, Mom!");


        Console.WriteLine("\nA static method closed over the first argument (String).");
        // The delegate must omit the first argument of the method.
        // A string is passed as the firstArgument parameter, and 
        // the delegate is bound to this string. Use delegate type 
        // D3 with static method M2. 
        //
        d3 = (D3) Delegate.CreateDelegate(typeof(D3), 
            "Hello, World!", mi2);

        // Each time the delegate is invoked, the same string is
        // used.
        d3();
    }
}

/* This code example produces the following output:

An instance method closed over C.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 42, s = Hi, Mom!

An open instance method.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 5280, s = Hi, Mom!

An open static method.
Static method M2 on C:  s = Hello, World!
Static method M2 on C:  s = Hi, Mom!

A static method closed over the first argument (String).
Static method M2 on C:  s = Hello, World!
 */
Imports System.Reflection
Imports System.Security.Permissions

' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C, ByVal s As String) 
Public Delegate Sub D2(ByVal s As String) 
Public Delegate Sub D3() 

' A sample class with an instance method and a Shared method.
'
Public Class C
    Private id As Integer
    Public Sub New(ByVal id As Integer) 
        Me.id = id
    End Sub

    Public Sub M1(ByVal s As String) 
        Console.WriteLine("Instance method M1 on C:  id = {0}, s = {1}", _
            Me.id, s)
    End Sub
    
    Public Shared Sub M2(ByVal s As String) 
        Console.WriteLine("Shared method M2 on C:  s = {0}", s)
    End Sub
End Class

Public Class Example
    
    Public Shared Sub Main() 

        Dim c1 As New C(42)
        
        ' Get a MethodInfo for each method.
        '
        Dim mi1 As MethodInfo = GetType(C).GetMethod("M1", _
            BindingFlags.Public Or BindingFlags.Instance)
        Dim mi2 As MethodInfo = GetType(C).GetMethod("M2", _
            BindingFlags.Public Or BindingFlags.Static)
        
        Dim d1 As D1
        Dim d2 As D2
        Dim d3 As D3
        
        
        Console.WriteLine(vbLf & "An instance method closed over C.")
        ' In this case, the delegate and the
        ' method must have the same list of argument types; use
        ' delegate type D2 with instance method M1.
        '
        Dim test As [Delegate] = _
            [Delegate].CreateDelegate(GetType(D2), c1, mi1, False)

        ' Because False was specified for throwOnBindFailure 
        ' in the call to CreateDelegate, the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if mi1 happened to represent a method of 
        ' some class other than C).
        '
        If test IsNot Nothing Then
            d2 = CType(test, D2)

            ' The same instance of C is used every time the
            ' delegate is invoked.
            d2("Hello, World!")
            d2("Hi, Mom!")
        End If
        
        
        Console.WriteLine(vbLf & "An open instance method.")
        ' In this case, the delegate has one more 
        ' argument than the instance method; this argument comes
        ' at the beginning, and represents the hidden instance
        ' argument of the instance method. Use delegate type D1
        ' with instance method M1.
        '
        d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)
        
        ' An instance of C must be passed in each time the 
        ' delegate is invoked.
        '
        d1(c1, "Hello, World!")
        d1(New C(5280), "Hi, Mom!")
        
        
        Console.WriteLine(vbLf & "An open Shared method.")
        ' In this case, the delegate and the method must 
        ' have the same list of argument types; use delegate type
        ' D2 with Shared method M2.
        '
        d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)
        
        ' No instances of C are involved, because this is a Shared
        ' method. 
        '
        d2("Hello, World!")
        d2("Hi, Mom!")
        
        
        Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
        ' The delegate must omit the first argument of the method.
        ' A string is passed as the firstArgument parameter, and 
        ' the delegate is bound to this string. Use delegate type 
        ' D3 with Shared method M2. 
        '
        d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)
        
        ' Each time the delegate is invoked, the same string is
        ' used.
        d3()
    
    End Sub
End Class

' This code example produces the following output:
'
'An instance method closed over C.
'Instance method M1 on C:  id = 42, s = Hello, World!
'Instance method M1 on C:  id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C:  id = 42, s = Hello, World!
'Instance method M1 on C:  id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C:  s = Hello, World!
'Shared method M2 on C:  s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C:  s = Hello, World!
' 

Ejemplo 2Example 2

En el ejemplo de código siguiente se muestra la compatibilidad de los tipos de parámetro y los tipos de valor devuelto.The following code example demonstrates compatibility of parameter types and return types.

Nota

En este ejemplo de código CreateDelegate(Type, MethodInfo) se usa la sobrecarga del método.This code example uses the CreateDelegate(Type, MethodInfo) method overload. El uso de otras sobrecargas que toman MethodInfo es similar.The use of other overloads that take MethodInfo is similar.

En el ejemplo de código se define una Base clase base denominada y Derived una clase denominada que Basese deriva de.The code example defines a base class named Base and a class named Derived that derives from Base. La clase derivada tiene un static métodoShared (en Visual Basic) denominado MyMethod con un parámetro de tipo Base y un tipo de valor Deriveddevuelto de.The derived class has a static (Shared in Visual Basic) method named MyMethod with one parameter of type Base and a return type of Derived. En el ejemplo de código también se define Example un delegado denominado que tiene un Derived parámetro de tipo y un Basetipo de valor devuelto de.The code example also defines a delegate named Example that has one parameter of type Derived and a return type of Base.

En el ejemplo de código se muestra que Example el delegado denominado se puede usar para MyMethodrepresentar el método.The code example demonstrates that the delegate named Example can be used to represent the method MyMethod. El método se puede enlazar al delegado porque:The method can be bound to the delegate because:

  • El tipo de parámetro del delegado (Derived) es más restrictivo que el tipo de parámetro de MyMethod (Base), de modo que siempre es seguro pasar el argumento del delegado a MyMethod.The parameter type of the delegate (Derived) is more restrictive than the parameter type of MyMethod (Base), so that it is always safe to pass the argument of the delegate to MyMethod.

  • El tipo de valor MyMethod devuelto de (Derived) es más restrictivo que el tipo de parámetro delBasedelegado (), de modo que siempre es seguro convertir el tipo de valor devuelto del método al tipo de valor devuelto del delegado.The return type of MyMethod (Derived) is more restrictive than the parameter type of the delegate (Base), so that it is always safe to cast the return type of the method to the return type of the delegate.

El ejemplo de código no genera ningún resultado.The code example produces no output.

using namespace System;
using namespace System::Reflection;

// Define two classes to use in the demonstration, a base class and 
// a class that derives from it.
//
public ref class Base {};

public ref class Derived : Base
{
    // Define a static method to use in the demonstration. The method 
    // takes an instance of Base and returns an instance of Derived.  
    // For the purposes of the demonstration, it is not necessary for 
    // the method to do anything useful. 
    //
public:
    static Derived^ MyMethod(Base^ arg)
    {
        Base^ dummy = arg;
        return gcnew Derived();
    }
};

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base^ Example(Derived^ arg);

void main()
{
    // The binding flags needed to retrieve MyMethod.
    BindingFlags flags = BindingFlags::Public | BindingFlags::Static;

    // Get a MethodInfo that represents MyMethod.
    MethodInfo^ minfo = Derived::typeid->GetMethod("MyMethod", flags);

    // Demonstrate contravariance of parameter types and covariance
    // of return types by using the delegate Example to represent
    // MyMethod. The delegate binds to the method because the
    // parameter of the delegate is more restrictive than the 
    // parameter of the method (that is, the delegate accepts an
    // instance of Derived, which can always be safely passed to
    // a parameter of type Base), and the return type of MyMethod
    // is more restrictive than the return type of Example (that
    // is, the method returns an instance of Derived, which can
    // always be safely cast to type Base). 
    //
    Example^ ex = 
        (Example^) Delegate::CreateDelegate(Example::typeid, minfo);

    // Execute MyMethod using the delegate Example.
    //        
    Base^ b = ex(gcnew Derived());
}
using System;
using System.Reflection;

// Define two classes to use in the demonstration, a base class and 
// a class that derives from it.
//
public class Base {}

public class Derived : Base
{
    // Define a static method to use in the demonstration. The method 
    // takes an instance of Base and returns an instance of Derived.  
    // For the purposes of the demonstration, it is not necessary for 
    // the method to do anything useful. 
    //
    public static Derived MyMethod(Base arg)
    {
        Base dummy = arg;
        return new Derived();
    }
}

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example(Derived arg);

class Test
{
    public static void Main()
    {
        // The binding flags needed to retrieve MyMethod.
        BindingFlags flags = BindingFlags.Public | BindingFlags.Static;

        // Get a MethodInfo that represents MyMethod.
        MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);

        // Demonstrate contravariance of parameter types and covariance
        // of return types by using the delegate Example to represent
        // MyMethod. The delegate binds to the method because the
        // parameter of the delegate is more restrictive than the 
        // parameter of the method (that is, the delegate accepts an
        // instance of Derived, which can always be safely passed to
        // a parameter of type Base), and the return type of MyMethod
        // is more restrictive than the return type of Example (that
        // is, the method returns an instance of Derived, which can
        // always be safely cast to type Base). 
        //
        Example ex = 
            (Example) Delegate.CreateDelegate(typeof(Example), minfo);

        // Execute MyMethod using the delegate Example.
        //        
        Base b = ex(new Derived());
    }
}
Imports System.Reflection

' Define two classes to use in the demonstration, a base class and 
' a class that derives from it.
'
Public Class Base
End Class

Public Class Derived
    Inherits Base

    ' Define a Shared method to use in the demonstration. The method 
    ' takes an instance of Base and returns an instance of Derived.  
    ' For the purposes of the demonstration, it is not necessary for 
    ' the method to do anything useful. 
    '
    Public Shared Function MyMethod(ByVal arg As Base) As Derived
        Dim dummy As Base = arg
        Return New Derived()
    End Function

End Class

' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base

Module Test

    Sub Main()

        ' The binding flags needed to retrieve MyMethod.
        Dim flags As BindingFlags = _
            BindingFlags.Public Or BindingFlags.Static

        ' Get a MethodInfo that represents MyMethod.
        Dim minfo As MethodInfo = _
            GetType(Derived).GetMethod("MyMethod", flags)

        ' Demonstrate contravariance of parameter types and covariance
        ' of return types by using the delegate Example to represent
        ' MyMethod. The delegate binds to the method because the
        ' parameter of the delegate is more restrictive than the 
        ' parameter of the method (that is, the delegate accepts an
        ' instance of Derived, which can always be safely passed to
        ' a parameter of type Base), and the return type of MyMethod
        ' is more restrictive than the return type of Example (that
        ' is, the method returns an instance of Derived, which can
        ' always be safely cast to type Base). 
        '
        Dim ex As Example = CType( _
            [Delegate].CreateDelegate(GetType(Example), minfo), _
            Example _
        )

        ' Execute MyMethod using the delegate Example.
        '        
        Dim b As Base = ex(New Derived())
    End Sub
End Module

Ejemplo 3Example 3

En el ejemplo de código siguiente se muestran todos los métodos que un único tipo de delegado CreateDelegate puede representar, utilizando el método para crear los delegados.The following code example shows all the methods a single delegate type can represent, using the CreateDelegate method to create the delegates.

Nota

Hay dos sobrecargas del CreateDelegate método que especifican firstArgument y MethodInfo, su funcionalidad es la misma, salvo que una permite especificar si se va a producir un error al enlazar y la otra siempre produce una excepción.There are two overloads of the CreateDelegate method that specify firstArgument and a MethodInfo; their functionality is the same except that one allows you to specify whether to throw on failure to bind, and the other always throws. En este ejemplo de código se usan las dos sobrecargas.This code example uses both overloads.

En el ejemplo de código se definen C dos Fclases, y, y D un tipo de delegado con Cun argumento de tipo.The code example defines two classes, C and F, and a delegate type D with one argument of type C. Las clases M1tienen métodos estáticos y de instancia coincidentes, M3, C y M4, y la clase M2 también tiene un método de instancia que no tiene argumentos.The classes have matching static and instance methods M1, M3, and M4, and class C also has an instance method M2 that has no arguments.

Una tercera clase denominada Example contiene el código que crea los delegados.A third class named Example contains the code that creates the delegates.

  • Los delegados se crean M1 para el C método de Finstancia de tipo y tipo; cada uno se cierra en una instancia del tipo respectivo.Delegates are created for instance method M1 of type C and type F; each is closed over an instance of the respective type. El M1 método de C tipo muestra ID las propiedades de la instancia enlazada y del argumento.Method M1 of type C displays the ID properties of the bound instance and of the argument.

  • Se crea un delegado para el M2 método de Ctipo.A delegate is created for method M2 of type C. Se trata de un delegado de instancia abierto, en el que el argumento del delegado representa el primer argumento oculto en el método de instancia.This is an open instance delegate, in which the argument of the delegate represents the hidden first argument on the instance method. El método no tiene ningún otro argumento.The method has no other arguments. Se llama como si fuera un método estático.It is called as if it were a static method.

  • Los delegados se crean M3 para el C método estático Fde tipo y tipo; son delegados estáticos abiertos.Delegates are created for static method M3 of type C and type F; these are open static delegates.

  • Por último, los delegados se M4 crean para C el método Festático de tipo y tipo; cada método tiene el tipo declarativo como primer argumento y se proporciona una instancia del tipo, por lo que los delegados se cierran en sus primeros argumentos. .Finally, delegates are created for static method M4 of type C and type F; each method has the declaring type as its first argument, and an instance of the type is supplied, so the delegates are closed over their first arguments. El M4 método de C tipo muestra ID las propiedades de la instancia enlazada y del argumento.Method M4 of type C displays the ID properties of the bound instance and of the argument.

using System;
using System.Reflection;
using System.Security.Permissions;

// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
//
public delegate void D(C c);

// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
//
public class C
{
    private int id;
    public int ID { get { return id; }}
    public C(int id) { this.id = id; }

    public void M1(C c) 
    { 
        Console.WriteLine("Instance method M1(C c) on C:  this.id = {0}, c.ID = {1}",
            this.id, c.ID);
    }
  
    public void M2() 
    { 
        Console.WriteLine("Instance method M2() on C:  this.id = {0}",
            this.id);
    }
  
    public static void M3(C c)
    { 
        Console.WriteLine("Static method M3(C c) on C:  c.ID = {0}", c.ID); 
    }

    public static void M4(C c1, C c2) 
    { 
        Console.WriteLine("Static method M4(C c1, C c2) on C:  c1.ID = {0}, c2.ID = {1}",
            c1.ID, c2.ID);
    }
}

public class F
{
    public void M1(C c) 
    { 
        Console.WriteLine("Instance method M1(C c) on F:  c.ID = {0}",
            c.ID);
    }
  
    public static void M3(C c)
    { 
        Console.WriteLine("Static method M3(C c) on F:  c.ID = {0}", c.ID); 
    }

    public static void M4(F f, C c) 
    { 
        Console.WriteLine("Static method M4(F f, C c) on F:  c.ID = {0}",
            c.ID);
    }
}


public class Example
{
    public static void Main()
    {
        C c1 = new C(42);
        C c2 = new C(1491);
        F f1 = new F();

        D d;

        // Instance method with one argument of type C.
        MethodInfo cmi1 = typeof(C).GetMethod("M1"); 
        // Instance method with no arguments.
        MethodInfo cmi2 = typeof(C).GetMethod("M2"); 
        // Static method with one argument of type C.
        MethodInfo cmi3 = typeof(C).GetMethod("M3"); 
        // Static method with two arguments of type C.
        MethodInfo cmi4 = typeof(C).GetMethod("M4"); 

        // Instance method with one argument of type C.
        MethodInfo fmi1 = typeof(F).GetMethod("M1");
        // Static method with one argument of type C.
        MethodInfo fmi3 = typeof(F).GetMethod("M3"); 
        // Static method with an argument of type F and an argument 
        // of type C.
        MethodInfo fmi4 = typeof(F).GetMethod("M4"); 

        Console.WriteLine("\nAn instance method on any type, with an argument of type C.");
        // D can represent any instance method that exactly matches its
        // signature. Methods on C and F are shown here.
        //
        d = (D) Delegate.CreateDelegate(typeof(D), c1, cmi1);
        d(c2);
        d = (D) Delegate.CreateDelegate(typeof(D), f1, fmi1);
        d(c2);

        Console.WriteLine("\nAn instance method on C with no arguments.");
        // D can represent an instance method on C that has no arguments;
        // in this case, the argument of D represents the hidden first
        // argument of any instance method. The delegate acts like a 
        // static method, and an instance of C must be passed each time
        // it is invoked.
        //
        d = (D) Delegate.CreateDelegate(typeof(D), null, cmi2);
        d(c1);

        Console.WriteLine("\nA static method on any type, with an argument of type C.");
        // D can represent any static method with the same signature.
        // Methods on F and C are shown here.
        //
        d = (D) Delegate.CreateDelegate(typeof(D), null, cmi3);
        d(c1);
        d = (D) Delegate.CreateDelegate(typeof(D), null, fmi3);
        d(c1);

        Console.WriteLine("\nA static method on any type, with an argument of");
        Console.WriteLine("    that type and an argument of type C.");
        // D can represent any static method with one argument of the
        // type the method belongs and a second argument of type C.
        // In this case, the method is closed over the instance of
        // supplied for the its first argument, and acts like an instance
        // method. Methods on F and C are shown here.
        //
        d = (D) Delegate.CreateDelegate(typeof(D), c1, cmi4);
        d(c2);
        Delegate test = 
            Delegate.CreateDelegate(typeof(D), f1, fmi4, false);

        // This final example specifies false for throwOnBindFailure 
        // in the call to CreateDelegate, so the variable 'test'
        // contains Nothing if the method fails to bind (for 
        // example, if fmi4 happened to represent a method of  
        // some class other than F).
        //
        if (test != null)
        {
            d = (D) test;
            d(c2);
        }
    }
}

/* This code example produces the following output:

An instance method on any type, with an argument of type C.
Instance method M1(C c) on C:  this.id = 42, c.ID = 1491
Instance method M1(C c) on F:  c.ID = 1491

An instance method on C with no arguments.
Instance method M2() on C:  this.id = 42

A static method on any type, with an argument of type C.
Static method M3(C c) on C:  c.ID = 42
Static method M3(C c) on F:  c.ID = 42

A static method on any type, with an argument of
    that type and an argument of type C.
Static method M4(C c1, C c2) on C:  c1.ID = 42, c2.ID = 1491
Static method M4(F f, C c) on F:  c.ID = 1491
*/
Imports System.Reflection
Imports System.Security.Permissions

' Declare a delegate type. The object of this code example
' is to show all the methods this delegate can bind to.
'
Public Delegate Sub D(ByVal c As C) 

' Declare two sample classes, C and F. Class C has an ID
' property so instances can be identified.
'
Public Class C

    Private _id As Integer

    Public ReadOnly Property ID() As Integer 
        Get
            Return _id
        End Get
    End Property

    Public Sub New(ByVal newId As Integer) 
        Me._id = newId
    End Sub
    
    Public Sub M1(ByVal c As C) 
        Console.WriteLine("Instance method M1(c As C) on C:  this.id = {0}, c.ID = {1}", _
            Me.id, c.ID)
    End Sub
    
    Public Sub M2() 
        Console.WriteLine("Instance method M2() on C:  this.id = {0}", Me.id)
    End Sub
    
    Public Shared Sub M3(ByVal c As C) 
        Console.WriteLine("Shared method M3(c As C) on C:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M4(ByVal c1 As C, ByVal c2 As C) 
        Console.WriteLine("Shared method M4(c1 As C, c2 As C) on C:  c1.ID = {0}, c2.ID = {1}", _
            c1.ID, c2.ID)
    End Sub
End Class


Public Class F
    
    Public Sub M1(ByVal c As C) 
        Console.WriteLine("Instance method M1(c As C) on F:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M3(ByVal c As C) 
        Console.WriteLine("Shared method M3(c As C) on F:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M4(ByVal f As F, ByVal c As C) 
        Console.WriteLine("Shared method M4(f As F, c As C) on F:  c.ID = {0}", c.ID)
    End Sub
End Class

Public Class Example
    
    Public Shared Sub Main() 

        Dim c1 As New C(42)
        Dim c2 As New C(1491)
        Dim f1 As New F()
        
        Dim d As D
        
        ' Instance method with one argument of type C.
        Dim cmi1 As MethodInfo = GetType(C).GetMethod("M1")
        ' Instance method with no arguments.
        Dim cmi2 As MethodInfo = GetType(C).GetMethod("M2")
        ' Shared method with one argument of type C.
        Dim cmi3 As MethodInfo = GetType(C).GetMethod("M3")
        ' Shared method with two arguments of type C.
        Dim cmi4 As MethodInfo = GetType(C).GetMethod("M4")
        
        ' Instance method with one argument of type C.
        Dim fmi1 As MethodInfo = GetType(F).GetMethod("M1")
        ' Shared method with one argument of type C.
        Dim fmi3 As MethodInfo = GetType(F).GetMethod("M3")
        ' Shared method with an argument of type F and an 
        ' argument of type C.
        Dim fmi4 As MethodInfo = GetType(F).GetMethod("M4")
        
        Console.WriteLine(vbLf & "An instance method on any type, with an argument of type C.")
        ' D can represent any instance method that exactly matches its
        ' signature. Methods on C and F are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi1), D)
        d(c2)
        d = CType([Delegate].CreateDelegate(GetType(D), f1, fmi1), D)
        d(c2)
        
        Console.WriteLine(vbLf & "An instance method on C with no arguments.")
        ' D can represent an instance method on C that has no arguments;
        ' in this case, the argument of D represents the hidden first
        ' argument of any instance method. The delegate acts like a 
        ' Shared method, and an instance of C must be passed each time
        ' it is invoked.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi2), D)
        d(c1)
        
        Console.WriteLine(vbLf & "A Shared method on any type, with an argument of type C.")
        ' D can represent any Shared method with the same signature.
        ' Methods on F and C are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi3), D)
        d(c1)
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, fmi3), D)
        d(c1)
        
        Console.WriteLine(vbLf & "A Shared method on any type, with an argument of")
        Console.WriteLine("    that type and an argument of type C.")
        ' D can represent any Shared method with one argument of the
        ' type the method belongs and a second argument of type C.
        ' In this case, the method is closed over the instance of
        ' supplied for the its first argument, and acts like an instance
        ' method. Methods on F and C are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi4), D)
        d(c2)
        Dim test As [Delegate] = _
            [Delegate].CreateDelegate(GetType(D), f1, fmi4, false)

        ' This final example specifies False for throwOnBindFailure 
        ' in the call to CreateDelegate, so the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if fmi4 happened to represent a method of  
        ' some class other than F).
        '
        If test IsNot Nothing Then
            d = CType(test, D)
            d(c2)
        End If
    
    End Sub
End Class

' This code example produces the following output:
'
'An instance method on any type, with an argument of type C.
'Instance method M1(c As C) on C:  this.id = 42, c.ID = 1491
'Instance method M1(c As C) on F:  c.ID = 1491
'
'An instance method on C with no arguments.
'Instance method M2() on C:  this.id = 42
'
'A Shared method on any type, with an argument of type C.
'Shared method M3(c As C) on C:  c.ID = 42
'Shared method M3(c As C) on F:  c.ID = 42
'
'A Shared method on any type, with an argument of
'    that type and an argument of type C.
'Shared method M4(c1 As C, c2 As C) on C:  c1.ID = 42, c2.ID = 1491
'Shared method M4(f As F, c As C) on F:  c.ID = 1491
'

Comentarios

Llamar a esta sobrecarga de método equivale a llamar CreateDelegate(Type, Object, MethodInfo, Boolean) a la sobrecarga del método true y throwOnBindFailureespecificar para.Calling this method overload is equivalent to calling the CreateDelegate(Type, Object, MethodInfo, Boolean) method overload and specifying true for throwOnBindFailure. Estas dos sobrecargas proporcionan la manera más flexible de crear delegados.These two overloads provide the most flexible way to create delegates. Puede utilizarlos para crear delegados para métodos estáticos o de instancia y, opcionalmente, para especificar el primer argumento.You can use them to create delegates for either static or instance methods, and optionally to specify the first argument.

Nota

Si no proporciona un primer argumento, use la sobrecarga del CreateDelegate(Type, MethodInfo) método para mejorar el rendimiento.If you do not supply a first argument, use the CreateDelegate(Type, MethodInfo) method overload for better performance.

El tipo de delegado y el método deben tener tipos de valor devueltos compatibles.The delegate type and the method must have compatible return types. Es decir, el tipo de valor method devuelto de debe ser asignable al tipo de typevalor devuelto de.That is, the return type of method must be assignable to the return type of type.

Si firstArgument se proporciona, se pasa a method cada vez que se invoca el delegado; firstArgument se dice que está enlazado al delegado y se dice que el delegado está cerrado sobre su primer argumento.If firstArgument is supplied, it is passed to method every time the delegate is invoked; firstArgument is said to be bound to the delegate, and the delegate is said to be closed over its first argument. Si method es static ( method firstArgument en Visual Basic), la lista de argumentos proporcionada al invocar al delegado incluye todos los parámetros excepto el primero; si es un método de instancia, se pasa a la instancia oculta.Shared parámetro (representado por this en C#, o por Me en Visual Basic).If method is static (Shared in Visual Basic), the argument list supplied when invoking the delegate includes all parameters except the first; if method is an instance method, then firstArgument is passed to the hidden instance parameter (represented by this in C#, or by Me in Visual Basic).

Si firstArgument se proporciona, el primer parámetro de method debe ser un tipo de referencia y firstArgument debe ser compatible con ese tipo.If firstArgument is supplied, the first parameter of method must be a reference type, and firstArgument must be compatible with that type.

Importante

Si method es static ( Object enVisualBasicValueType) y sufirstArgument primer parámetro es de tipo o, puede ser un tipo de valor.SharedIf method is static (Shared in Visual Basic) and its first parameter is of type Object or ValueType, then firstArgument can be a value type. En este caso firstArgument , se aplica automáticamente la conversión boxing.In this case firstArgument is automatically boxed. La conversión boxing automática no se produce para ningún otro argumento, como lo haría C# en una llamada de función o Visual Basic.Automatic boxing does not occur for any other arguments, as it would in a C# or Visual Basic function call.

Si firstArgument es una referencia nula y method es un método de instancia, el resultado depende de las firmas del tipo type de delegado y de method:If firstArgument is a null reference and method is an instance method, the result depends on the signatures of the delegate type type and of method:

  • Si la firma de type incluye explícitamente el primer parámetro oculto methodde, se dice que el delegado representa un método de instancia abierto.If the signature of type explicitly includes the hidden first parameter of method, the delegate is said to represent an open instance method. Cuando se invoca el delegado, el primer argumento de la lista de argumentos se pasa al parámetro de instancia oculto de method.When the delegate is invoked, the first argument in the argument list is passed to the hidden instance parameter of method.

  • Si las firmas de y method type coinciden (es decir, todos los tipos de parámetro son compatibles), se dice que el delegado está cerrado en una referencia nula.If the signatures of method and type match (that is, all parameter types are compatible), then the delegate is said to be closed over a null reference. La invocación del delegado es como llamar a un método de instancia en una instancia null, lo que no es una cosa especialmente útil.Invoking the delegate is like calling an instance method on a null instance, which is not a particularly useful thing to do.

Si firstArgument es una referencia nula y method es static, el resultado depende de las firmas del tipo type de delegado y de method:If firstArgument is a null reference and method is static, the result depends on the signatures of the delegate type type and of method:

  • Si la firma de method y type coincide (es decir, todos los tipos de parámetro son compatibles), se dice que el delegado representa un método estático abierto.If the signature of method and type match (that is, all parameter types are compatible), the delegate is said to represent an open static method. Este es el caso más común de los métodos estáticos.This is the most common case for static methods. En este caso, puede obtener un rendimiento ligeramente mejor mediante la sobrecarga CreateDelegate(Type, MethodInfo) del método.In this case, you can get slightly better performance by using the CreateDelegate(Type, MethodInfo) method overload.

  • Si la firma de type comienza con el segundo parámetro de method y el resto de los tipos de parámetro son compatibles, se dice que el delegado está cerrado en una referencia nula.If the signature of type begins with the second parameter of method and the rest of the parameter types are compatible, then the delegate is said to be closed over a null reference. Cuando se invoca el delegado, se pasa una referencia nula al primer parámetro de method.When the delegate is invoked, a null reference is passed to the first parameter of method.

Nota

A partir de ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess , este método se puede usar para tener acceso a métodos no públicos si el llamador se ha concedido con la marca y si el conjunto de permisos de los métodos no públicos está restringido al conjunto de permisos del llamador o a un .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1subconjunto. mismo.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public methods if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public methods is restricted to the caller's grant set, or a subset thereof. (Consulte consideraciones de seguridad para la reflexión).(See Security Considerations for Reflection.)

Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Tipos de parámetro y tipo de valor devuelto compatiblesCompatible Parameter Types and Return Type

Los tipos de parámetro y el tipo de valor devuelto de un delegado deben ser compatibles con los tipos de parámetro y el tipo de valor devuelto del método que representa el delegado. no es necesario que los tipos coincidan exactamente.The parameter types and return type of a delegate must be compatible with the parameter types and return type of the method the delegate represents; the types do not have to match exactly.

Nota

En la .NET Framework versión 1,0 y 1,1, los tipos deben coincidir exactamente.In the .NET Framework version 1.0 and 1.1, the types must match exactly.

Un parámetro de un delegado es compatible con el parámetro correspondiente de un método si el tipo del parámetro del delegado es más restrictivo que el del método, porque así se garantiza que el argumento que se pase al delegado también se podrá pasar de forma segura al método.A parameter of a delegate is compatible with the corresponding parameter of a method if the type of the delegate parameter is more restrictive than the type of the method parameter, because this guarantees that an argument passed to the delegate can be passed safely to the method.

De forma similar, el tipo de valor devuelto de un delegado es compatible con el tipo de valor devuelto de un método si el del método es más restrictivo que el del delegado, porque así se garantiza que el tipo de valor devuelto por el método se puede convertir con seguridad al tipo de valor devuelto del delegado.Similarly, the return type of a delegate is compatible with the return type of a method if the return type of the method is more restrictive than the return type of the delegate, because this guarantees that the return value of the method can be cast safely to the return type of the delegate.

Por ejemplo, un delegado con un parámetro de tipo Hashtable y un tipo de Object valor devuelto puede representar un método con un parámetro Object de tipo y un valor devuelto de tipo Hashtable.For example, a delegate with a parameter of type Hashtable and a return type of Object can represent a method with a parameter of type Object and a return value of type Hashtable.

Determinar los métodos que un delegado puede representarDetermining the Methods a Delegate Can Represent

Otra manera útil de pensar en la flexibilidad proporcionada por esta sobrecarga de CreateDelegate es que cualquier delegado determinado puede representar cuatro combinaciones diferentes de la firma de método y el tipo de método (estático frente a instancia).Another useful way to think of the flexibility provided by this overload of CreateDelegate is that any given delegate can represent four different combinations of method signature and method kind (static versus instance). Considere la posibilidad de D usar un tipo de delegado Ccon un argumento de tipo.Consider a delegate type D with one argument of type C. A continuación se describen los D métodos que pueden representar y omitir el tipo de valor devuelto, ya que debe coincidir en todos los casos:The following describes the methods D can represent, ignoring the return type since it must match in all cases:

  • Dpuede representar cualquier método de instancia que tenga exactamente un argumento de Ctipo, independientemente del tipo al que pertenezca el método de instancia.D can represent any instance method that has exactly one argument of type C, regardless of what type the instance method belongs to. Cuando CreateDelegate se llama a firstArgument , es una instancia del tipo method al que pertenece y se dice que el delegado resultante está cerrado en esa instancia.When CreateDelegate is called, firstArgument is an instance of the type method belongs to, and the resulting delegate is said to be closed over that instance. (Trivialmente, D también se puede cerrar en una referencia nula si firstArgument es una referencia nula).(Trivially, D can also be closed over a null reference if firstArgument is a null reference.)

  • Dpuede representar un método de instancia C de que no tiene ningún argumento.D can represent an instance method of C that has no arguments. Cuando CreateDelegate se llama a firstArgument , es una referencia nula.When CreateDelegate is called, firstArgument is a null reference. El delegado resultante representa un método de instancia abierto y se debe proporcionar C una instancia de cada vez que se invoca.The resulting delegate represents an open instance method, and an instance of C must be supplied each time it is invoked.

  • Dpuede representar un método estático que toma un argumento de tipo Cy ese método puede pertenecer a cualquier tipo.D can represent a static method that takes one argument of type C, and that method can belong to any type. Cuando CreateDelegate se llama a firstArgument , es una referencia nula.When CreateDelegate is called, firstArgument is a null reference. El delegado resultante representa un método estático abierto y se debe proporcionar una C instancia de cada vez que se invoca.The resulting delegate represents an open static method, and an instance of C must be supplied each time it is invoked.

  • Dpuede representar un método estático que pertenece al tipo F y tiene dos argumentos, de tipo F y tipo C.D can represent a static method that belongs to type F and has two arguments, of type F and type C. Cuando CreateDelegate se llama a firstArgument , es una instancia Fde.When CreateDelegate is called, firstArgument is an instance of F. El delegado resultante representa un método estático que se cierra en esa instancia de F.The resulting delegate represents a static method that is closed over that instance of F. Tenga en cuenta que en el F caso C de que y sean del mismo tipo, el método estático tiene dos argumentos de ese tipo.Note that in the case where F and C are the same type, the static method has two arguments of that type. (En este caso, D se cierra en una referencia nula si firstArgument es una referencia nula).(In this case, D is closed over a null reference if firstArgument is a null reference.)

Seguridad

ReflectionPermission
Cuando se invoca enlazado en tiempo de ejecución mediante InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])mecanismos como.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Consulte también:

CreateDelegate(Type, Type, String)

Crea un delegado del tipo especificado que representa el método estático especificado de la clase especificada.Creates a delegate of the specified type that represents the specified static method of the specified class.

public:
 static Delegate ^ CreateDelegate(Type ^ type, Type ^ target, System::String ^ method);
public static Delegate CreateDelegate (Type type, Type target, string method);
static member CreateDelegate : Type * Type * string -> Delegate

Parámetros

type
Type

Type de delegado que se va a crear.The Type of delegate to create.

target
Type

Type que representa la clase que implementa method.The Type representing the class that implements method.

method
String

Nombre del método estático que va a representar el delegado.The name of the static method that the delegate is to represent.

Devoluciones

Delegado del tipo especificado que representa el método estático especificado de la clase especificada.A delegate of the specified type that represents the specified static method of the specified class.

Excepciones

type es null.type is null.

O bien-or- target es null.target is null.

O bien-or- method es null.method is null.

type no hereda MulticastDelegate.type does not inherit MulticastDelegate.

O bien-or- type no es un RuntimeType.type is not a RuntimeType. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

O bien-or- target no es un RuntimeType.target is not a RuntimeType.

O bien-or- target es un tipo genérico abierto.target is an open generic type. Es decir, su propiedad ContainsGenericParameters es true.That is, its ContainsGenericParameters property is true.

O bien-or- method no es un método static (método Shared en Visual Basic).method is not a static method (Shared method in Visual Basic).

O bien-or- method no se puede enlazar (por ejemplo, porque no se encuentra) y throwOnBindFailure es true.method cannot be bound, for example because it cannot be found, and throwOnBindFailure is true.

No se encuentra el método Invoke de type.The Invoke method of type is not found.

El autor de la llamada no tiene los permisos necesarios para acceder a method.The caller does not have the permissions necessary to access method.

Comentarios

Este método solo crea delegados para métodos estáticos.This method creates delegates for static methods only. Un método de instancia es un método que está asociado a una instancia de una clase; un método estático es un método que está asociado a la propia clase.An instance method is a method that is associated with an instance of a class; a static method is a method that is associated with the class itself.

Esta sobrecarga del método es equivalente a llamar CreateDelegate(Type, Type, String, Boolean, Boolean) a la sobrecarga del método false , ignoreCase especificando throwOnBindFailurepara y true para.This method overload is equivalent to calling the CreateDelegate(Type, Type, String, Boolean, Boolean) method overload, specifying false for ignoreCase and true for throwOnBindFailure.

Nota

A partir de ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess , este método se puede usar para tener acceso a métodos no públicos si el llamador se ha concedido con la marca y si el conjunto de permisos de los métodos no públicos está restringido al conjunto de permisos del llamador o a un .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1subconjunto. mismo.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public methods if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public methods is restricted to the caller's grant set, or a subset thereof. (Consulte consideraciones de seguridad para la reflexión).(See Security Considerations for Reflection.)

Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Seguridad

ReflectionPermission
Cuando se invoca enlazado en tiempo de ejecución mediante InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])mecanismos como.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Consulte también:

CreateDelegate(Type, MethodInfo)

Crea un delegado del tipo especificado para representar el método estático especificado.Creates a delegate of the specified type to represent the specified static method.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Reflection::MethodInfo ^ method);
public static Delegate CreateDelegate (Type type, System.Reflection.MethodInfo method);
static member CreateDelegate : Type * System.Reflection.MethodInfo -> Delegate

Parámetros

type
Type

Type de delegado que se va a crear.The Type of delegate to create.

method
MethodInfo

MethodInfo que describe el método estático o de instancia que va a representar el delegado.The MethodInfo describing the static or instance method the delegate is to represent. Sólo se admiten métodos estáticos en las versiones 1.0 y 1.1 de .NET Framework.Only static methods are supported in the .NET Framework version 1.0 and 1.1.

Devoluciones

Delegado del tipo especificado para representar el método estático especificado.A delegate of the specified type to represent the specified static method.

Excepciones

type es null.type is null.

O bien-or- method es null.method is null.

type no hereda MulticastDelegate.type does not inherit MulticastDelegate.

o bien-or- type no es un RuntimeType.type is not a RuntimeType. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

O bien-or- method no es un método estático y la versión de .NET Framework es 1.0 o 1.1.method is not a static method, and the .NET Framework version is 1.0 or 1.1.

O bien-or- No se puede enlazar method.method cannot be bound.

o bien-or- method no es un RuntimeMethodInfo.method is not a RuntimeMethodInfo. Vea Tipos de reflexión en tiempo de ejecución.See Runtime Types in Reflection.

No se encuentra el método Invoke de type.The Invoke method of type is not found.

El autor de la llamada no tiene los permisos necesarios para acceder a method.The caller does not have the permissions necessary to access method.

Ejemplos

Esta sección contiene dos ejemplos de código.This section contains two code examples. En el primer ejemplo se muestran los dos tipos de delegados que se pueden crear con esta sobrecarga del método: abrir sobre un método de instancia y abrir sobre un método estático.The first example demonstrates the two kinds of delegates that can be created with this method overload: open over an instance method and open over a static method.

En el segundo ejemplo de código se muestran los tipos de parámetros compatibles y los tipos de valor devueltos.The second code example demonstrates compatible parameter types and return types.

Ejemplo 1Example 1

En el ejemplo de código siguiente se muestran las dos maneras en que se puede crear un delegado CreateDelegate mediante esta sobrecarga del método.The following code example demonstrates the two ways a delegate can be created using this overload of the CreateDelegate method.

Nota

Hay dos sobrecargas del CreateDelegate método que especifican un MethodInfo , pero no un primer argumento; su funcionalidad es la misma, salvo que se puede especificar si se va a producir un error al enlazar, y el otro siempre produce una excepción.There are two overloads of the CreateDelegate method that specify a MethodInfo but not a first argument; their functionality is the same except that one allows you to specify whether to throw on failure to bind, and the other always throws. En este ejemplo de código se usan las dos sobrecargas.This code example uses both overloads.

En el ejemplo se declara una C clase con un método M2 estático y un método M1de instancia, y dos tipos D1 de delegado: toma C una instancia de y una D2 cadena y toma una cadena.The example declares a class C with a static method M2 and an instance method M1, and two delegate types: D1 takes an instance of C and a string, and D2 takes a string.

Una segunda clase denominada Example contiene el código que crea los delegados.A second class named Example contains the code that creates the delegates.

  • Se crea un delegado D1de tipo, que representa un método de instancia abierto, para el M1método de instancia.A delegate of type D1, representing an open instance method, is created for the instance method M1. Se debe pasar una instancia de cuando se invoca el delegado.An instance must be passed when the delegate is invoked.

  • Se crea un delegado D2de tipo que representa un método estático abierto para el método M2estático.A delegate of type D2, representing an open static method, is created for the static method M2.

using System;
using System.Reflection;
using System.Security.Permissions;

// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();

// A sample class with an instance method and a static method.
//
public class C
{
    private int id;
    public C(int id) { this.id = id; }

    public void M1(string s) 
    { 
        Console.WriteLine("Instance method M1 on C:  id = {0}, s = {1}",
            this.id, s);
    }
  
    public static void M2(string s)
    { 
        Console.WriteLine("Static method M2 on C:  s = {0}", s); 
    }
}

public class Example
{
    public static void Main()
    {
        C c1 = new C(42);

        // Get a MethodInfo for each method.
        //
        MethodInfo mi1 = typeof(C).GetMethod("M1", 
            BindingFlags.Public | BindingFlags.Instance);
        MethodInfo mi2 = typeof(C).GetMethod("M2",
            BindingFlags.Public | BindingFlags.Static);

        D1 d1;
        D2 d2;
        D3 d3;


        Console.WriteLine("\nAn instance method closed over C.");
        // In this case, the delegate and the
        // method must have the same list of argument types; use
        // delegate type D2 with instance method M1.
        //
        Delegate test = 
            Delegate.CreateDelegate(typeof(D2), c1, mi1, false);

        // Because false was specified for throwOnBindFailure 
        // in the call to CreateDelegate, the variable 'test'
        // contains null if the method fails to bind (for 
        // example, if mi1 happened to represent a method of  
        // some class other than C).
        //
        if (test != null)
        {
            d2 = (D2) test;

            // The same instance of C is used every time the 
            // delegate is invoked.
            d2("Hello, World!");
            d2("Hi, Mom!");
        }


        Console.WriteLine("\nAn open instance method.");
        // In this case, the delegate has one more 
        // argument than the instance method; this argument comes
        // at the beginning, and represents the hidden instance
        // argument of the instance method. Use delegate type D1
        // with instance method M1.
        //
        d1 = (D1) Delegate.CreateDelegate(typeof(D1), null, mi1);

        // An instance of C must be passed in each time the 
        // delegate is invoked.
        //
        d1(c1, "Hello, World!");
        d1(new C(5280), "Hi, Mom!");


        Console.WriteLine("\nAn open static method.");
        // In this case, the delegate and the method must 
        // have the same list of argument types; use delegate type
        // D2 with static method M2.
        //
        d2 = (D2) Delegate.CreateDelegate(typeof(D2), null, mi2);

        // No instances of C are involved, because this is a static
        // method. 
        //
        d2("Hello, World!");
        d2("Hi, Mom!");


        Console.WriteLine("\nA static method closed over the first argument (String).");
        // The delegate must omit the first argument of the method.
        // A string is passed as the firstArgument parameter, and 
        // the delegate is bound to this string. Use delegate type 
        // D3 with static method M2. 
        //
        d3 = (D3) Delegate.CreateDelegate(typeof(D3), 
            "Hello, World!", mi2);

        // Each time the delegate is invoked, the same string is
        // used.
        d3();
    }
}

/* This code example produces the following output:

An instance method closed over C.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 42, s = Hi, Mom!

An open instance method.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 5280, s = Hi, Mom!

An open static method.
Static method M2 on C:  s = Hello, World!
Static method M2 on C:  s = Hi, Mom!

A static method closed over the first argument (String).
Static method M2 on C:  s = Hello, World!
 */
Imports System.Reflection
Imports System.Security.Permissions

' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C, ByVal s As String) 
Public Delegate Sub D2(ByVal s As String) 
Public Delegate Sub D3() 

' A sample class with an instance method and a Shared method.
'
Public Class C
    Private id As Integer
    Public Sub New(ByVal id As Integer) 
        Me.id = id
    End Sub

    Public Sub M1(ByVal s As String) 
        Console.WriteLine("Instance method M1 on C:  id = {0}, s = {1}", _
            Me.id, s)
    End Sub
    
    Public Shared Sub M2(ByVal s As String) 
        Console.WriteLine("Shared method M2 on C:  s = {0}", s)
    End Sub
End Class

Public Class Example
    
    Public Shared Sub Main() 

        Dim c1 As New C(42)
        
        ' Get a MethodInfo for each method.
        '
        Dim mi1 As MethodInfo = GetType(C).GetMethod("M1", _
            BindingFlags.Public Or BindingFlags.Instance)
        Dim mi2 As MethodInfo = GetType(C).GetMethod("M2", _
            BindingFlags.Public Or BindingFlags.Static)
        
        Dim d1 As D1
        Dim d2 As D2
        Dim d3 As D3
        
        
        Console.WriteLine(vbLf & "An instance method closed over C.")
        ' In this case, the delegate and the
        ' method must have the same list of argument types; use
        ' delegate type D2 with instance method M1.
        '
        Dim test As [Delegate] = _
            [Delegate].CreateDelegate(GetType(D2), c1, mi1, False)

        ' Because False was specified for throwOnBindFailure 
        ' in the call to CreateDelegate, the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if mi1 happened to represent a method of 
        ' some class other than C).
        '
        If test IsNot Nothing Then
            d2 = CType(test, D2)

            ' The same instance of C is used every time the
            ' delegate is invoked.
            d2("Hello, World!")
            d2("Hi, Mom!")
        End If
        
        
        Console.WriteLine(vbLf & "An open instance method.")
        ' In this case, the delegate has one more 
        ' argument than the instance method; this argument comes
        ' at the beginning, and represents the hidden instance
        ' argument of the instance method. Use delegate type D1
        ' with instance method M1.
        '
        d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)
        
        ' An instance of C must be passed in each time the 
        ' delegate is invoked.
        '
        d1(c1, "Hello, World!")
        d1(New C(5280), "Hi, Mom!")
        
        
        Console.WriteLine(vbLf & "An open Shared method.")
        ' In this case, the delegate and the method must 
        ' have the same list of argument types; use delegate type
        ' D2 with Shared method M2.
        '
        d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)
        
        ' No instances of C are involved, because this is a Shared
        ' method. 
        '
        d2("Hello, World!")
        d2("Hi, Mom!")
        
        
        Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
        ' The delegate must omit the first argument of the method.
        ' A string is passed as the firstArgument parameter, and 
        ' the delegate is bound to this string. Use delegate type 
        ' D3 with Shared method M2. 
        '
        d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)
        
        ' Each time the delegate is invoked, the same string is
        ' used.
        d3()
    
    End Sub
End Class

' This code example produces the following output:
'
'An instance method closed over C.
'Instance method M1 on C:  id = 42, s = Hello, World!
'Instance method M1 on C:  id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C:  id = 42, s = Hello, World!
'Instance method M1 on C:  id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C:  s = Hello, World!
'Shared method M2 on C:  s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C:  s = Hello, World!
' 

Ejemplo 2Example 2

En el ejemplo de código siguiente se muestra la compatibilidad de los tipos de parámetro y los tipos de valor devuelto.The following code example demonstrates compatibility of parameter types and return types.

En el ejemplo de código se define una Base clase base denominada y Derived una clase denominada que Basese deriva de.The code example defines a base class named Base and a class named Derived that derives from Base. La clase derivada tiene un static métodoShared (en Visual Basic) denominado MyMethod con un parámetro de tipo Base y un tipo de valor Deriveddevuelto de.The derived class has a static (Shared in Visual Basic) method named MyMethod with one parameter of type Base and a return type of Derived. En el ejemplo de código también se define Example un delegado denominado que tiene un Derived parámetro de tipo y un Basetipo de valor devuelto de.The code example also defines a delegate named Example that has one parameter of type Derived and a return type of Base.

En el ejemplo de código se muestra que Example el delegado denominado se puede usar para MyMethodrepresentar el método.The code example demonstrates that the delegate named Example can be used to represent the method MyMethod. El método se puede enlazar al delegado porque:The method can be bound to the delegate because:

  • El tipo de parámetro del delegado (Derived) es más restrictivo que el tipo de parámetro de MyMethod (Base), de modo que siempre es seguro pasar el argumento del delegado a MyMethod.The parameter type of the delegate (Derived) is more restrictive than the parameter type of MyMethod (Base), so that it is always safe to pass the argument of the delegate to MyMethod.

  • El tipo de valor MyMethod devuelto de (Derived) es más restrictivo que el tipo de parámetro delBasedelegado (), de modo que siempre es seguro convertir el tipo de valor devuelto del método al tipo de valor devuelto del delegado.The return type of MyMethod (Derived) is more restrictive than the parameter type of the delegate (Base), so that it is always safe to cast the return type of the method to the return type of the delegate.

El ejemplo de código no genera ningún resultado.The code example produces no output.

using namespace System;
using namespace System::Reflection;

// Define two classes to use in the demonstration, a base class and 
// a class that derives from it.
//
public ref class Base {};

public ref class Derived : Base
{
    // Define a static method to use in the demonstration. The method 
    // takes an instance of Base and returns an instance of Derived.  
    // For the purposes of the demonstration, it is not necessary for 
    // the method to do anything useful. 
    //
public:
    static Derived^ MyMethod(Base^ arg)
    {
        Base^ dummy = arg;
        return gcnew Derived();
    }
};

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base^ Example(Derived^ arg);

void main()
{
    // The binding flags needed to retrieve MyMethod.
    BindingFlags flags = BindingFlags::Public | BindingFlags::Static;

    // Get a MethodInfo that represents MyMethod.
    MethodInfo^ minfo = Derived::typeid->GetMethod("MyMethod", flags);

    // Demonstrate contravariance of parameter types and covariance
    // of return types by using the delegate Example to represent
    // MyMethod. The delegate binds to the method because the
    // parameter of the delegate is more restrictive than the 
    // parameter of the method (that is, the delegate accepts an
    // instance of Derived, which can always be safely passed to
    // a parameter of type Base), and the return type of MyMethod
    // is more restrictive than the return type of Example (that
    // is, the method returns an instance of Derived, which can
    // always be safely cast to type Base). 
    //
    Example^ ex = 
        (Example^) Delegate::CreateDelegate(Example::typeid, minfo);

    // Execute MyMethod using the delegate Example.
    //        
    Base^ b = ex(gcnew Derived());
}
using System;
using System.Reflection;

// Define two classes to use in the demonstration, a base class and 
// a class that derives from it.
//
public class Base {}

public class Derived : Base
{
    // Define a static method to use in the demonstration. The method 
    // takes an instance of Base and returns an instance of Derived.  
    // For the purposes of the demonstration, it is not necessary for 
    // the method to do anything useful. 
    //
    public static Derived MyMethod(Base arg)
    {
        Base dummy = arg;
        return new Derived();
    }
}

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example(Derived arg);

class Test
{
    public static void Main()
    {
        // The binding flags needed to retrieve MyMethod.
        BindingFlags flags = BindingFlags.Public | BindingFlags.Static;

        // Get a MethodInfo that represents MyMethod.
        MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);

        // Demonstrate contravariance of parameter types and covariance
        // of return types by using the delegate Example to represent
        // MyMethod. The delegate binds to the method because the
        // parameter of the delegate is more restrictive than the 
        // parameter of the method (that is, the delegate accepts an
        // instance of Derived, which can always be safely passed to
        // a parameter of type Base), and the return type of MyMethod
        // is more restrictive than the return type of Example (that
        // is, the method returns an instance of Derived, which can
        // always be safely cast to type Base). 
        //
        Example ex = 
            (Example) Delegate.CreateDelegate(typeof(Example), minfo);

        // Execute MyMethod using the delegate Example.
        //        
        Base b = ex(new Derived());
    }
}
Imports System.Reflection

' Define two classes to use in the demonstration, a base class and 
' a class that derives from it.
'
Public Class Base
End Class

Public Class Derived
    Inherits Base

    ' Define a Shared method to use in the demonstration. The method 
    ' takes an instance of Base and returns an instance of Derived.  
    ' For the purposes of the demonstration, it is not necessary for 
    ' the method to do anything useful. 
    '
    Public Shared Function MyMethod(ByVal arg As Base) As Derived
        Dim dummy As Base = arg
        Return New Derived()
    End Function

End Class

' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base

Module Test

    Sub Main()

        ' The binding flags needed to retrieve MyMethod.
        Dim flags As BindingFlags = _
            BindingFlags.Public Or BindingFlags.Static

        ' Get a MethodInfo that represents MyMethod.
        Dim minfo As MethodInfo = _
            GetType(Derived).GetMethod("MyMethod", flags)

        ' Demonstrate contravariance of parameter types and covariance
        ' of return types by using the delegate Example to represent
        ' MyMethod. The delegate binds to the method because the
        ' parameter of the delegate is more restrictive than the 
        ' parameter of the method (that is, the delegate accepts an
        ' instance of Derived, which can always be safely passed to
        ' a parameter of type Base), and the return type of MyMethod
        ' is more restrictive than the return type of Example (that
        ' is, the method returns an instance of Derived, which can
        ' always be safely cast to type Base). 
        '
        Dim ex As Example = CType( _
            [Delegate].CreateDelegate(GetType(Example), minfo), _
            Example _
        )

        ' Execute MyMethod using the delegate Example.
        '        
        Dim b As Base = ex(New Derived())
    End Sub
End Module

Comentarios

En la .NET Framework versión 1,0 y 1,1, esta sobrecarga del método crea delegados solo para métodos estáticos.In the .NET Framework version 1.0 and 1.1, this method overload creates delegates for static methods only. En la .NET Framework versión 2,0, esta sobrecarga del método también puede crear delegados de método de instancia abierto; es decir, los delegados que proporcionan explícitamente el primer argumento oculto de los métodos de instancia.In the .NET Framework version 2.0, this method overload also can create open instance method delegates; that is, delegates that explicitly supply the hidden first argument of instance methods. Para obtener una explicación detallada, vea la sobrecarga CreateDelegate(Type, Object, MethodInfo) de método más general, que permite crear todas las combinaciones de los delegados abiertos o cerrados para los métodos estáticos o de instancia, y, opcionalmente, especificar un primer argumento.For a detailed explanation, see the more general CreateDelegate(Type, Object, MethodInfo) method overload, which allows you to create all combinations of open or closed delegates for instance or static methods, and optionally to specify a first argument.

Nota

Esta sobrecarga del método se debe utilizar cuando el delegado no está cerrado sobre su primer argumento, porque es algo más rápido en ese caso.This method overload should be used when the delegate is not closed over its first argument, because it is somewhat faster in that case.

Esta sobrecarga del método es equivalente a llamar CreateDelegate(Type, MethodInfo, Boolean) a la sobrecarga del método true y throwOnBindFailureespecificar para.This method overload is equivalent to calling the CreateDelegate(Type, MethodInfo, Boolean) method overload and specifying true for throwOnBindFailure.

Nota

A partir de ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess , este método se puede usar para tener acceso a métodos no públicos si el llamador se ha concedido con la marca y si el conjunto de permisos de los métodos no públicos está restringido al conjunto de permisos del llamador o a un .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1subconjunto. mismo.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public methods if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public methods is restricted to the caller's grant set, or a subset thereof. (Consulte consideraciones de seguridad para la reflexión).(See Security Considerations for Reflection.)

Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Tipos de parámetro y tipo de valor devuelto compatiblesCompatible Parameter Types and Return Type

En la .NET Framework versión 2,0, los tipos de parámetro y el tipo de valor devuelto de un delegado creado con esta sobrecarga del método deben ser compatibles con los tipos de parámetro y el tipo de valor devuelto del método que representa el delegado. no es necesario que los tipos coincidan exactamente.In the .NET Framework version 2.0, the parameter types and return type of a delegate created using this method overload must be compatible with the parameter types and return type of the method the delegate represents; the types do not have to match exactly. Esto representa una flexibilización del comportamiento de enlace en la .NET Framework versión 1,0 y 1,1, donde los tipos deben coincidir exactamente.This represents a relaxation of the binding behavior in the .NET Framework version 1.0 and 1.1, where the types must match exactly.

Un parámetro de un delegado es compatible con el parámetro correspondiente de un método si el tipo del parámetro del delegado es más restrictivo que el del método, porque así se garantiza que el argumento que se pase al delegado también se podrá pasar de forma segura al método.A parameter of a delegate is compatible with the corresponding parameter of a method if the type of the delegate parameter is more restrictive than the type of the method parameter, because this guarantees that an argument passed to the delegate can be passed safely to the method.

De forma similar, el tipo de valor devuelto de un delegado es compatible con el tipo de valor devuelto de un método si el del método es más restrictivo que el del delegado, porque así se garantiza que el tipo de valor devuelto por el método se puede convertir con seguridad al tipo de valor devuelto del delegado.Similarly, the return type of a delegate is compatible with the return type of a method if the return type of the method is more restrictive than the return type of the delegate, because this guarantees that the return value of the method can be cast safely to the return type of the delegate.

Por ejemplo, un delegado con un parámetro de tipo Hashtable y un tipo de Object valor devuelto puede representar un método con un parámetro Object de tipo y un valor devuelto de tipo Hashtable.For example, a delegate with a parameter of type Hashtable and a return type of Object can represent a method with a parameter of type Object and a return value of type Hashtable.

Seguridad

ReflectionPermission
Cuando se invoca enlazado en tiempo de ejecución mediante InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])mecanismos como.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Consulte también:

Se aplica a