Delegate.CreateDelegate 方法

定义

创建指定类型的委托。Creates a delegate of the specified type.

重载

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

使用用于指定是否区分大小写的值和针对绑定失败的指定行为,创建指定类型的委托,该委托表示指定类的指定静态方法。Creates a delegate of the specified type that represents the specified static method of the specified class, with the specified case-sensitivity and the specified behavior on failure to bind.

CreateDelegate(Type, Type, String, Boolean)

使用用于指定是否区分大小写的值创建指定类型的委托,该委托表示指定类的指定静态方法。Creates a delegate of the specified type that represents the specified static method of the specified class, with the specified case-sensitivity.

CreateDelegate(Type, Object, String, Boolean)

创建指定类型的委托,该委托表示要按指定的大小写敏感度对指定类实例调用的指定实例方法。Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance with the specified case-sensitivity.

CreateDelegate(Type, Object, MethodInfo, Boolean)

使用指定的第一个参数和针对绑定失败的指定行为,创建表示指定的静态方法或实例方法的指定类型的委托。Creates a delegate of the specified type that represents the specified static or instance method, with the specified first argument and the specified behavior on failure to bind.

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

使用用于指定是否区分大小写的值和针对绑定失败的指定行为,创建指定类型的委托,该委托表示要对指定类实例调用的指定实例方法。Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance, with the specified case-sensitivity and the specified behavior on failure to bind.

CreateDelegate(Type, MethodInfo, Boolean)

使用针对绑定失败的指定行为,创建用于表示指定静态方法的指定类型的委托。Creates a delegate of the specified type to represent the specified static method, with the specified behavior on failure to bind.

CreateDelegate(Type, Object, String)

创建指定类型的委托,该委托表示要对指定的类实例调用的指定实例方法。Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance.

CreateDelegate(Type, Object, MethodInfo)

使用指定的第一个参数创建指定类型的委托,该委托表示指定的静态方法或实例方法。Creates a delegate of the specified type that represents the specified static or instance method, with the specified first argument.

CreateDelegate(Type, Type, String)

创建指定类型的委托,该委托表示指定类的指定静态方法。Creates a delegate of the specified type that represents the specified static method of the specified class.

CreateDelegate(Type, MethodInfo)

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

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

使用用于指定是否区分大小写的值和针对绑定失败的指定行为,创建指定类型的委托,该委托表示指定类的指定静态方法。Creates a delegate of the specified type that represents the specified static method of the specified class, with the specified case-sensitivity and the specified behavior on failure to bind.

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

参数

type
Type

要创建的委托的 TypeThe Type of delegate to create.

target
Type

表示实现 method 的类的 TypeThe Type representing the class that implements method.

method
String

委托要表示的静态方法的名称。The name of the static method that the delegate is to represent.

ignoreCase
Boolean

一个布尔值,它指示在比较方法名称时是否忽略大小写。A Boolean indicating whether to ignore the case when comparing the name of the method.

throwOnBindFailure
Boolean

如果无法绑定 method 时引发异常,则为 true;否则为 falsetrue to throw an exception if method cannot be bound; otherwise, false.

返回

指定类型的委托,该委托表示指定类的指定静态方法。A delegate of the specified type that represents the specified static method of the specified class.

异常

typenulltype is null.

- 或 --or- targetnulltarget is null.

- 或 --or- methodnullmethod is null.

type 不继承 MulticastDelegatetype does not inherit MulticastDelegate.

- 或 --or- type 不是 RuntimeTypetype is not a RuntimeType. 请参阅反射中的运行时类型See Runtime Types in Reflection.

-or- target 不是 RuntimeTypetarget is not a RuntimeType.

-or- target 为开放式泛型类型。target is an open generic type. 也就是说,其 ContainsGenericParameters 属性为 trueThat is, its ContainsGenericParameters property is true.

-or- method 不是 static 方法(在 Visual Basic 中为 Shared 方法)。method is not a static method (Shared method in Visual Basic).

- 或 --or- 无法绑定 method,例如因为找不到它,并且 throwOnBindFailuretruemethod cannot be bound, for example because it cannot be found, and throwOnBindFailure is true.

找不到 typeInvoke 方法。The Invoke method of type is not found.

调用方没有访问 method 所必需的权限。The caller does not have the permissions necessary to access method.

注解

此方法仅为静态方法创建委托。This method creates delegates for static methods only. 实例方法是与类的实例关联的方法;静态方法是与类自身相关联的方法。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.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,此方法可用于访问非公共方法,前提是已使用标志授予调用方,而非公共方法的授予集限制为调用方的授予集或子集.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.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. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

CreateDelegate(Type, Type, String, Boolean)

使用用于指定是否区分大小写的值创建指定类型的委托,该委托表示指定类的指定静态方法。Creates a delegate of the specified type that represents the specified static method of the specified class, with the specified case-sensitivity.

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

参数

type
Type

要创建的委托的 TypeThe Type of delegate to create.

target
Type

表示实现 method 的类的 TypeThe Type representing the class that implements method.

method
String

委托要表示的静态方法的名称。The name of the static method that the delegate is to represent.

ignoreCase
Boolean

一个布尔值,它指示在比较方法名称时是否忽略大小写。A Boolean indicating whether to ignore the case when comparing the name of the method.

返回

指定类型的委托,该委托表示指定类的指定静态方法。A delegate of the specified type that represents the specified static method of the specified class.

异常

typenulltype is null.

-or- targetnulltarget is null.

-or- methodnullmethod is null.

type 不继承 MulticastDelegatetype does not inherit MulticastDelegate.

-or- type 不是 RuntimeTypetype is not a RuntimeType. 请参阅反射中的运行时类型See Runtime Types in Reflection.

-or- target 不是 RuntimeTypetarget is not a RuntimeType.

- 或 --or- target 为开放式泛型类型。target is an open generic type. 也就是说,其 ContainsGenericParameters 属性为 trueThat is, its ContainsGenericParameters property is true.

-or- method 不是 static 方法(在 Visual Basic 中为 Shared 方法)。method is not a static method (Shared method in Visual Basic).

-or- 无法绑定 method,例如因为找不到它。method cannot be bound, for example because it cannot be found.

找不到 typeInvoke 方法。The Invoke method of type is not found.

调用方没有访问 method 所必需的权限。The caller does not have the permissions necessary to access method.

注解

此方法仅为静态方法创建委托。This method creates delegates for static methods only. 实例方法是与类的实例关联的方法;静态方法是与类自身相关联的方法。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.

此方法重载等效于调用CreateDelegate(Type, Type, String, Boolean, Boolean)方法重载,并为throwOnBindFailure指定trueThis method overload is equivalent to calling the CreateDelegate(Type, Type, String, Boolean, Boolean) method overload, specifying true for throwOnBindFailure.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,此方法可用于访问非公共方法,前提是已使用标志授予调用方,而非公共方法的授予集限制为调用方的授予集或子集.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.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. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

CreateDelegate(Type, Object, String, Boolean)

创建指定类型的委托,该委托表示要按指定的大小写敏感度对指定类实例调用的指定实例方法。Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance with the specified case-sensitivity.

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

参数

type
Type

要创建的委托的 TypeThe Type of delegate to create.

target
Object

类实例,对其调用 methodThe class instance on which method is invoked.

method
String

委托要表示的实例方法的名称。The name of the instance method that the delegate is to represent.

ignoreCase
Boolean

一个布尔值,它指示在比较方法名称时是否忽略大小写。A Boolean indicating whether to ignore the case when comparing the name of the method.

返回

指定的类型的委托,表示要对指定的类实例调用的指定的实例方法。A delegate of the specified type that represents the specified instance method to invoke on the specified class instance.

异常

typenulltype is null.

-or- targetnulltarget is null.

- 或 --or- methodnullmethod is null.

type 不继承 MulticastDelegatetype does not inherit MulticastDelegate.

- 或 --or- type 不是 RuntimeTypetype is not a RuntimeType. 请参阅反射中的运行时类型See Runtime Types in Reflection.

-or- method 不是实例方法。method is not an instance method.

-or- 无法绑定 method,例如因为找不到它。method cannot be bound, for example because it cannot be found.

找不到 typeInvoke 方法。The Invoke method of type is not found.

调用方没有访问 method 所必需的权限。The caller does not have the permissions necessary to access method.

注解

此方法只为实例方法创建委托。This method creates delegates for instance methods only. 实例方法是与类的实例关联的方法;静态方法是与类自身相关联的方法。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.

此方法重载等效于调用CreateDelegate(Type, Object, String, Boolean, Boolean)方法重载,并为throwOnBindFailure指定trueThis method overload is equivalent to calling the CreateDelegate(Type, Object, String, Boolean, Boolean) method overload, specifying true for throwOnBindFailure.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,此方法可用于访问非公共方法,前提是已使用标志授予调用方,而非公共方法的授予集限制为调用方的授予集或子集.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.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. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

CreateDelegate(Type, Object, MethodInfo, Boolean)

使用指定的第一个参数和针对绑定失败的指定行为,创建表示指定的静态方法或实例方法的指定类型的委托。Creates a delegate of the specified type that represents the specified static or instance method, with the specified first argument and the specified behavior on failure to bind.

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

参数

type
Type

一个 Type,表示要创建的委托的类型。A Type representing the type of delegate to create.

firstArgument
Object

一个 Object,它是委托表示的方法的第一个参数。An Object that is the first argument of the method the delegate represents. 对于实例方法,它必须与实例类型兼容。For instance methods, it must be compatible with the instance type.

method
MethodInfo

描述该委托要表示的静态或实例方法的 MethodInfoThe MethodInfo describing the static or instance method the delegate is to represent.

throwOnBindFailure
Boolean

如果无法绑定 method 时引发异常,则为 true;否则为 falsetrue to throw an exception if method cannot be bound; otherwise, false.

返回

表示指定的静态方法或实例方法的指定类型的委托,如果 throwOnBindFailurenull,并且委托无法绑定到 method,则为 falseA 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.

异常

typenulltype is null.

-or- methodnullmethod is null.

type 不继承 MulticastDelegatetype does not inherit MulticastDelegate.

- 或 --or- type 不是 RuntimeTypetype is not a RuntimeType. 请参阅反射中的运行时类型See Runtime Types in Reflection.

-or- 无法绑定 method,且 throwOnBindFailuretruemethod cannot be bound, and throwOnBindFailure is true.

-or- method 不是 RuntimeMethodInfomethod is not a RuntimeMethodInfo. 请参阅反射中的运行时类型See Runtime Types in Reflection.

找不到 typeInvoke 方法。The Invoke method of type is not found.

调用方没有访问 method 所必需的权限。The caller does not have the permissions necessary to access method.

示例

本部分包含三个代码示例。This section contains three code examples. 第一个示例演示了可创建的四种委托:通过实例方法关闭、在实例方法上打开、通过静态方法打开和通过静态方法关闭。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.

第二个代码示例演示兼容的参数类型和返回类型。The second code example demonstrates compatible parameter types and return types.

第三个代码示例定义了一个委托类型,并显示委托类型可以表示的所有方法。The third code example defines a single delegate type, and shows all the methods that delegate type can represent.

示例1Example 1

下面的代码示例演示了使用此CreateDelegate方法重载可以创建委托的四种方法。The following code example demonstrates the four ways a delegate can be created using this overload of the CreateDelegate method.

备注

CreateDelegate方法有两个重载,它指定firstArgument和 a MethodInfo; 其功能相同,不同之处在于,它允许您指定是否要在绑定失败时引发,另一个始终引发。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. 此代码示例使用两个重载。This code example uses both overloads.

该示例使用静态方法C M2 、实例方法M1C三个委托类型来声明类: D1采用的实例和字符串, D2采用字符串, D3没有参数。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.

名为Example的第二个类包含创建委托的代码。A second class named Example contains the code that creates the delegates.

  • 为实例方法D2 C创建了一个类型的委托,该委托在的M1实例上关闭。A delegate of type D2, closed over an instance of C, is created for the instance method M1. 它使用不同的字符串调用,以表示始终使用的绑定实例CIt is invoked with different strings, to show that the bound instance of C is always used.

  • 为实例方法M1创建D1表示开放式实例方法的类型为的委托。A delegate of type D1, representing an open instance method, is created for the instance method M1. 调用委托时,必须传递一个实例。An instance must be passed when the delegate is invoked.

  • 为静态方法M2创建D2一个表示 open 静态方法的类型的委托。A delegate of type D2, representing an open static method, is created for the static method M2.

  • 最后,为静态方法D3 M2创建一个在字符串上关闭的类型的委托。Finally, a delegate of type D3, closed over a string, is created for the static method M2. 调用方法以显示它使用绑定的字符串。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!
' 

示例2Example 2

下面的代码示例演示参数类型和返回类型的兼容性。The following code example demonstrates compatibility of parameter types and return types.

备注

此代码示例使用CreateDelegate(Type, MethodInfo)方法重载。This code example uses the CreateDelegate(Type, MethodInfo) method overload. 使用采用MethodInfo的其他重载类似。The use of other overloads that take MethodInfo is similar.

此代码示例定义一个名为Base的基类和一个名为Derived的类Base,该类派生自。The code example defines a base class named Base and a class named Derived that derives from Base. 派生类具有一个名static MyMethodShared的(在 Visual Basic)方法,该方法具有Base一个类型为的Derived参数和一个返回类型。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. 此代码示例还定义了一个名Example为的委托,该委托Derived具有一个类型为的Base参数和一个返回类型。The code example also defines a delegate named Example that has one parameter of type Derived and a return type of Base.

此代码示例演示了可用于表示Example方法MyMethod的名为的委托。The code example demonstrates that the delegate named Example can be used to represent the method MyMethod. 方法可以绑定到委托,原因如下:The method can be bound to the delegate because:

  • 委托(Derived)的参数类型比MyMethodBase)的参数类型具有更强的限制,因此,将委托的参数传递给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.

  • MyMethodBase)的返回类型的限制性强于委托的参数类型(),因此,将方法的返回类型强制转换为委托的返回类型始终是安全的。DerivedThe 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.

此代码示例不生成输出。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

示例3Example 3

下面的代码示例演示一个委托类型可以表示的所有方法。The following code example shows all the methods a single delegate type can represent.

备注

CreateDelegate方法有两个重载,它指定firstArgument和 a MethodInfo; 其功能相同,不同之处在于,它允许您指定是否要在绑定失败时引发,另一个始终引发。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. 此代码示例使用两个重载。This code example uses both overloads.

此代码示例定义了两个CF:和,以及一个D类型C为的参数的委托类型。The code example defines two classes, C and F, and a delegate type D with one argument of type C. 类具有匹配的静态和实例方法M1M3M4,并且类C还具有一个不带参数M2的实例方法。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.

第三个名Example为的类包含创建委托的代码。A third class named Example contains the code that creates the delegates.

  • 为类型M1 C和类型F的实例方法创建委托; 每个委托都在各自类型的实例上关闭。Delegates are created for instance method M1 of type C and type F; each is closed over an instance of the respective type. ID类型M1 为的方法显示绑定实例和C参数的属性。Method M1 of type C displays the ID properties of the bound instance and of the argument.

  • 为类型M2 C的方法创建委托。A delegate is created for method M2 of type C. 这是一个打开的实例委托,其中委托的参数表示实例方法上隐藏的第一个参数。This is an open instance delegate, in which the argument of the delegate represents the hidden first argument on the instance method. 方法没有其他参数。The method has no other arguments.

  • 为类型M3 C和类型F的静态方法创建委托; 这些是开放式静态委托。Delegates are created for static method M3 of type C and type F; these are open static delegates.

  • 最后,为类型M4 C和类型F的静态方法创建委托; 每个方法都将声明类型作为其第一个参数,并提供类型的实例,因此这些委托在其第一个参数上关闭.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. ID类型M4 为的方法显示绑定实例和C参数的属性。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
'

注解

此方法重载和CreateDelegate(Type, Object, MethodInfo)方法重载(始终在绑定失败时引发)提供了最灵活的方法来创建委托。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. 可以使用这些方法为静态方法或实例方法创建委托,无论是使用第一个参数还是不使用第一个参数。You can use them to create delegates for either static or instance methods, with or without a first argument.

备注

如果不提供第一个参数,请使用CreateDelegate(Type, MethodInfo, Boolean)方法重载以获得更好的性能。If you do not supply a first argument, use the CreateDelegate(Type, MethodInfo, Boolean) method overload for better performance.

委托类型和方法必须具有兼容的返回类型。The delegate type and the method must have compatible return types. 也就是说,的method返回类型必须可分配给的返回type类型。That is, the return type of method must be assignable to the return type of type.

如果firstArgument提供了,则每次调用method委托时将传递到该委托;firstArgument被称为绑定到委托,并且委托被称为通过其第一个参数关闭。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. 如果methodstaticmethod firstArgument在 Visual Basic),则调用委托时提供的自变量列表包含除第一个以外的所有参数; 如果为实例方法,则将传递给隐藏的实例Shared参数(由this中C#的表示, Me在 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).

如果firstArgument提供了,则的method第一个参数必须是引用类型,并且firstArgument必须与该类型兼容。If firstArgument is supplied, the first parameter of method must be a reference type, and firstArgument must be compatible with that type.

重要

如果methodfirstArgument ValueType Object (在 Visual Basic 中),并且其第一个参数的类型为或,则可以是值类型。Shared staticIf method is static (Shared in Visual Basic) and its first parameter is of type Object or ValueType, then firstArgument can be a value type. 在这种firstArgument情况下,会自动装箱。In this case firstArgument is automatically boxed. 对于任何其他参数,都不会出现自动装箱,这与在C#或 Visual Basic 函数调用中一样。Automatic boxing does not occur for any other arguments, as it would in a C# or Visual Basic function call.

如果firstArgument是 null 引用并且method是实例方法,则结果取决于委托类型type和的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:

  • 如果的type签名显式包含隐藏的method第一个参数,则称委托表示一个开放式实例方法。If the signature of type explicitly includes the hidden first parameter of method, the delegate is said to represent an open instance method. 调用委托时,将参数列表中的第一个自变量传递给的隐藏实例参数methodWhen the delegate is invoked, the first argument in the argument list is passed to the hidden instance parameter of method.

  • 如果methodtype匹配的签名(即所有参数类型都兼容),则将委托称为空引用。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. 调用委托类似于在 null 实例上调用实例方法,这并不是特别有用的操作。Invoking the delegate is like calling an instance method on a null instance, which is not a particularly useful thing to do.

如果firstArgument是 null 引用并且method是静态的,则结果取决于委托类型type和的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:

  • 如果methodtype匹配的签名(即,所有参数类型都兼容),则委托称为表示开放式静态方法。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. 这是静态方法最常见的情况。This is the most common case for static methods. 在这种情况下,可以使用CreateDelegate(Type, MethodInfo, Boolean)方法重载获得略微更好的性能。In this case, you can get slightly better performance by using the CreateDelegate(Type, MethodInfo, Boolean) method overload.

  • 如果的签名type以的第二个method参数开始,而其余的参数类型是兼容的,则认为该委托是通过空引用关闭的。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. 调用委托时,空引用将传递给的第一个参数methodWhen the delegate is invoked, a null reference is passed to the first parameter of method.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,此方法可用于访问非公共方法,前提是已使用标志授予调用方,而非公共方法的授予集限制为调用方的授予集或子集.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.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. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

兼容的参数类型和返回类型Compatible Parameter Types and Return Type

委托的参数类型和返回类型必须与委托表示的方法的参数类型和返回类型兼容;类型不必完全匹配。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.

备注

在 .NET Framework 版本1.0 和1.1 中,类型必须完全匹配。In the .NET Framework version 1.0 and 1.1 the types must match exactly.

如果委托参数的类型的限制性强于方法参数的类型,则该委托的参数与该方法的相应参数兼容,因为这可保证传递给委托的参数可以安全地传递给方法。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.

同样,如果方法的返回类型的限制性强于委托的返回类型,则该委托的返回类型与该方法的返回类型兼容,因为这可保证方法的返回值可以安全地强制转换为委托的返回类型。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.

例如,具有Hashtable类型为的参数和返回类型的Object委托可以表示具有类型Object的参数和类型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.

确定委托可以表示的方法Determining the Methods a Delegate Can Represent

考虑此重载CreateDelegate提供的灵活性的另一种有用方法是,任何给定的委托都可以表示方法签名和方法类型(静态与实例)的四种不同组合。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). 请考虑一个具有D类型C为的参数的委托类型。Consider a delegate type D with one argument of type C. 下面描述了方法可以D表示的方法,忽略返回类型,因为它在所有情况下都必须匹配:The following describes the methods D can represent, ignoring the return type since it must match in all cases:

  • D可以表示任何具有一个类型C为的参数的任何实例方法,而不考虑该实例方法所属的类型。D can represent any instance method that has exactly one argument of type C, regardless of what type the instance method belongs to. CreateDelegate调用时, firstArgument是该类型method的一个实例,而所生成的委托则被称为关闭该实例。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. (完全, D如果firstArgumentnull,还可以通过空引用关闭。)(Trivially, D can also be closed over a null reference if firstArgument is null.)

  • D可以表示没有参数的实例C方法。D can represent an instance method of C that has no arguments. 调用CreateDelegate时, firstArgument为空引用。When CreateDelegate is called, firstArgument is a null reference. 生成的委托表示开放式实例方法, C必须在每次调用时提供实例。The resulting delegate represents an open instance method, and an instance of C must be supplied each time it is invoked.

  • D可以表示静态方法,该方法采用一个类型C的参数,该方法可以属于任何类型。D can represent a static method that takes one argument of type C, and that method can belong to any type. 调用CreateDelegate时, firstArgument为空引用。When CreateDelegate is called, firstArgument is a null reference. 生成的委托表示开放式静态方法, C必须在每次调用时提供实例。The resulting delegate represents an open static method, and an instance of C must be supplied each time it is invoked.

  • D可以表示属于类型F且具有两个类型F为的参数和类型C的静态方法。D can represent a static method that belongs to type F and has two arguments, of type F and type C. CreateDelegate调用时, firstArgument是的F实例。When CreateDelegate is called, firstArgument is an instance of F. 生成的委托表示在该实例F上关闭的静态方法。The resulting delegate represents a static method that is closed over that instance of F. 请注意,在FC的类型相同的情况下,静态方法具有该类型的两个参数。Note that in the case where F and C are the same type, the static method has two arguments of that type. (在这种情况D下,如果firstArgumentnull,则通过空引用关闭。)(In this case, D is closed over a null reference if firstArgument is null.)

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

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

使用用于指定是否区分大小写的值和针对绑定失败的指定行为,创建指定类型的委托,该委托表示要对指定类实例调用的指定实例方法。Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance, with the specified case-sensitivity and the specified behavior on failure to bind.

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

参数

type
Type

要创建的委托的 TypeThe Type of delegate to create.

target
Object

类实例,对其调用 methodThe class instance on which method is invoked.

method
String

委托要表示的实例方法的名称。The name of the instance method that the delegate is to represent.

ignoreCase
Boolean

一个布尔值,它指示在比较方法名称时是否忽略大小写。A Boolean indicating whether to ignore the case when comparing the name of the method.

throwOnBindFailure
Boolean

如果无法绑定 method 时引发异常,则为 true;否则为 falsetrue to throw an exception if method cannot be bound; otherwise, false.

返回

指定的类型的委托,表示要对指定的类实例调用的指定的实例方法。A delegate of the specified type that represents the specified instance method to invoke on the specified class instance.

异常

typenulltype is null.

- 或 --or- targetnulltarget is null.

-or- methodnullmethod is null.

type 不继承 MulticastDelegatetype does not inherit MulticastDelegate.

-or- type 不是 RuntimeTypetype is not a RuntimeType. 请参阅反射中的运行时类型See Runtime Types in Reflection.

-or- method 不是实例方法。method is not an instance method.

-or- 无法绑定 method,例如因为找不到它,并且 throwOnBindFailuretruemethod cannot be bound, for example because it cannot be found, and throwOnBindFailure is true.

找不到 typeInvoke 方法。The Invoke method of type is not found.

调用方没有访问 method 所必需的权限。The caller does not have the permissions necessary to access method.

注解

此方法只为实例方法创建委托。This method creates delegates for instance methods only. 实例方法是与类的实例关联的方法;静态方法是与类自身相关联的方法。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.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,此方法可用于访问非公共方法,前提是已使用标志授予调用方,而非公共方法的授予集限制为调用方的授予集或子集.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.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. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

CreateDelegate(Type, MethodInfo, Boolean)

使用针对绑定失败的指定行为,创建用于表示指定静态方法的指定类型的委托。Creates a delegate of the specified type to represent the specified static method, with the specified behavior on failure to bind.

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

参数

type
Type

要创建的委托的 TypeThe Type of delegate to create.

method
MethodInfo

描述该委托要表示的静态或实例方法的 MethodInfoThe MethodInfo describing the static or instance method the delegate is to represent.

throwOnBindFailure
Boolean

如果无法绑定 method 时引发异常,则为 true;否则为 falsetrue to throw an exception if method cannot be bound; otherwise, false.

返回

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

异常

typenulltype is null.

- 或 --or- methodnullmethod is null.

type 不继承 MulticastDelegatetype does not inherit MulticastDelegate.

-or- type 不是 RuntimeTypetype is not a RuntimeType. 请参阅反射中的运行时类型See Runtime Types in Reflection.

-or- 无法绑定 method,且 throwOnBindFailuretruemethod cannot be bound, and throwOnBindFailure is true.

-or- method 不是 RuntimeMethodInfomethod is not a RuntimeMethodInfo. 请参阅反射中的运行时类型See Runtime Types in Reflection.

找不到 typeInvoke 方法。The Invoke method of type is not found.

调用方没有访问 method 所必需的权限。The caller does not have the permissions necessary to access method.

示例

本部分包含两个代码示例。This section contains two code examples. 第一个示例演示可使用此方法重载创建的两种委托:通过实例方法打开并通过静态方法打开。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.

第二个代码示例演示兼容的参数类型和返回类型。The second code example demonstrates compatible parameter types and return types.

示例1Example 1

下面的代码示例演示了使用此CreateDelegate方法重载可以创建委托的两种方法。The following code example demonstrates the two ways a delegate can be created using this overload of the CreateDelegate method.

备注

CreateDelegate方法有两个重载,它MethodInfo指定但不指定第一个参数; 其功能是相同的,但前者允许您指定是否要在绑定失败时引发,另一个始终引发。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. 此代码示例使用两个重载。This code example uses both overloads.

该示例使用静态方法C M2 、实例方法M1C两个委托类型来声明类: D1使用实例和字符串,并D2使用字符串。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.

名为Example的第二个类包含创建委托的代码。A second class named Example contains the code that creates the delegates.

  • 为实例方法M1创建D1表示开放式实例方法的类型为的委托。A delegate of type D1, representing an open instance method, is created for the instance method M1. 调用委托时,必须传递一个实例。An instance must be passed when the delegate is invoked.

  • 为静态方法M2创建D2一个表示 open 静态方法的类型的委托。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!
' 

示例2Example 2

下面的代码示例演示参数类型和返回类型的兼容性。The following code example demonstrates compatibility of parameter types and return types.

备注

此代码示例使用CreateDelegate(Type, MethodInfo)方法重载。This code example uses the CreateDelegate(Type, MethodInfo) method overload. 使用采用MethodInfo的其他重载类似。The use of other overloads that take MethodInfo is similar.

此代码示例定义一个名为Base的基类和一个名为Derived的类Base,该类派生自。The code example defines a base class named Base and a class named Derived that derives from Base. 派生类具有一个名static MyMethodShared的(在 Visual Basic)方法,该方法具有Base一个类型为的Derived参数和一个返回类型。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. 此代码示例还定义了一个名Example为的委托,该委托Derived具有一个类型为的Base参数和一个返回类型。The code example also defines a delegate named Example that has one parameter of type Derived and a return type of Base.

此代码示例演示了可用于表示Example方法MyMethod的名为的委托。The code example demonstrates that the delegate named Example can be used to represent the method MyMethod. 方法可以绑定到委托,原因如下:The method can be bound to the delegate because:

  • 委托(Derived)的参数类型比MyMethodBase)的参数类型具有更强的限制,因此,将委托的参数传递给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.

  • MyMethodBase)的返回类型的限制性强于委托的参数类型(),因此,将方法的返回类型强制转换为委托的返回类型始终是安全的。DerivedThe 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.

此代码示例不生成输出。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

注解

此方法重载可以创建开放式静态方法委托和开放式实例方法委托,即公开实例方法的隐藏第一个参数的委托。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. 有关详细说明,请参阅更通用CreateDelegate(Type, Object, MethodInfo, Boolean)的方法重载,该重载允许您为实例或静态方法创建开放式或封闭式委托的所有组合。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.

备注

如果委托未通过其第一个参数关闭,则应使用此方法重载,因为在这种情况下,该委托的速度稍快。This method overload should be used when the delegate is not closed over its first argument, because it is somewhat faster in that case.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,此方法可用于访问非公共方法,前提是已使用标志授予调用方,而非公共方法的授予集限制为调用方的授予集或子集.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.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. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

兼容的参数类型和返回类型Compatible Parameter Types and Return Type

委托的参数类型和返回类型必须与委托表示的方法的参数类型和返回类型兼容;类型不必完全匹配。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.

备注

在 .NET Framework 版本1.0 和1.1 中,类型必须完全匹配。In the .NET Framework version 1.0 and 1.1, the types must match exactly.

如果委托参数的类型的限制性强于方法参数的类型,则该委托的参数与该方法的相应参数兼容,因为这可保证传递给委托的参数可以安全地传递给方法。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.

同样,如果方法的返回类型的限制性强于委托的返回类型,则该委托的返回类型与该方法的返回类型兼容,因为这可保证方法的返回值可以安全地强制转换为委托的返回类型。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.

例如,具有Hashtable类型为的参数和返回类型的Object委托可以表示具有类型Object的参数和类型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.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

CreateDelegate(Type, Object, String)

创建指定类型的委托,该委托表示要对指定的类实例调用的指定实例方法。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

参数

type
Type

要创建的委托的 TypeThe Type of delegate to create.

target
Object

类实例,对其调用 methodThe class instance on which method is invoked.

method
String

委托要表示的实例方法的名称。The name of the instance method that the delegate is to represent.

返回

指定的类型的委托,表示要对指定的类实例调用的指定的实例方法。A delegate of the specified type that represents the specified instance method to invoke on the specified class instance.

异常

typenulltype is null.

- 或 --or- targetnulltarget is null.

-or- methodnullmethod is null.

type 不继承 MulticastDelegatetype does not inherit MulticastDelegate.

-or- type 不是 RuntimeTypetype is not a RuntimeType. 请参阅反射中的运行时类型See Runtime Types in Reflection.

-or- method 不是实例方法。method is not an instance method.

-or- 无法绑定 method,例如因为找不到它。method cannot be bound, for example because it cannot be found.

找不到 typeInvoke 方法。The Invoke method of type is not found.

调用方没有访问 method 所必需的权限。The caller does not have the permissions necessary to access method.

注解

此方法只为实例方法创建委托。This method creates delegates for instance methods only. 实例方法是与类的实例关联的方法;静态方法是与类自身相关联的方法。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.

此方法重载等效于调用CreateDelegate(Type, Object, String, Boolean, Boolean)方法重载, ignoreCase并为指定falsetrue throwOnBindFailureThis method overload is equivalent to calling the CreateDelegate(Type, Object, String, Boolean, Boolean) method overload, specifying false for ignoreCase and true for throwOnBindFailure.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,此方法可用于访问非公共方法,前提是已使用标志授予调用方,而非公共方法的授予集限制为调用方的授予集或子集.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.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. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

CreateDelegate(Type, Object, MethodInfo)

使用指定的第一个参数创建指定类型的委托,该委托表示指定的静态方法或实例方法。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

参数

type
Type

要创建的委托的 TypeThe Type of delegate to create.

firstArgument
Object

委托要绑定到的对象,若要将 method 作为 static(在 Visual Basic 中为 Shared),则为 nullThe object to which the delegate is bound, or null to treat method as static (Shared in Visual Basic).

method
MethodInfo

描述该委托要表示的静态或实例方法的 MethodInfoThe MethodInfo describing the static or instance method the delegate is to represent.

返回

指定类型的委托,表示指定的静态或实例方法。A delegate of the specified type that represents the specified static or instance method.

异常

typenulltype is null.

- 或 --or- methodnullmethod is null.

type 不继承 MulticastDelegatetype does not inherit MulticastDelegate.

- 或 --or- type 不是 RuntimeTypetype is not a RuntimeType. 请参阅反射中的运行时类型See Runtime Types in Reflection.

- 或 --or- 无法绑定 methodmethod cannot be bound.

-or- method 不是 RuntimeMethodInfomethod is not a RuntimeMethodInfo. 请参阅反射中的运行时类型See Runtime Types in Reflection.

找不到 typeInvoke 方法。The Invoke method of type is not found.

调用方没有访问 method 所必需的权限。The caller does not have the permissions necessary to access method.

示例

本部分包含三个代码示例。This section contains three code examples. 第一个示例演示了可创建的四种委托:通过实例方法关闭、在实例方法上打开、通过静态方法打开和通过静态方法关闭。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.

第二个代码示例演示兼容的参数类型和返回类型。The second code example demonstrates compatible parameter types and return types.

第三个代码示例定义了一个委托类型,并显示委托类型可以表示的所有方法。The third code example defines a single delegate type, and shows all the methods that delegate type can represent.

示例1Example 1

下面的代码示例演示了使用此CreateDelegate方法重载可以创建委托的四种方法。The following code example demonstrates the four ways a delegate can be created using this overload of the CreateDelegate method.

备注

CreateDelegate方法有两个重载,它指定firstArgument和 a MethodInfo; 其功能相同,不同之处在于,它允许您指定是否要在绑定失败时引发,另一个始终引发。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. 此代码示例使用两个重载。This code example uses both overloads.

该示例使用静态方法C M2 、实例方法M1C三个委托类型来声明类: D1采用的实例和字符串, D2采用字符串, D3没有参数。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.

名为Example的第二个类包含创建委托的代码。A second class named Example contains the code that creates the delegates.

  • 为实例方法D2 C创建了一个类型的委托,该委托在的M1实例上关闭。A delegate of type D2, closed over an instance of C, is created for the instance method M1. 它使用不同的字符串调用,以表示始终使用的绑定实例CIt is invoked with different strings, to show that the bound instance of C is always used.

  • 为实例方法M1创建D1表示开放式实例方法的类型为的委托。A delegate of type D1, representing an open instance method, is created for the instance method M1. 调用委托时,必须传递一个实例。An instance must be passed when the delegate is invoked.

  • 为静态方法M2创建D2一个表示 open 静态方法的类型的委托。A delegate of type D2, representing an open static method, is created for the static method M2.

  • 最后,为静态方法D3 M2创建一个在字符串上关闭的类型的委托。Finally, a delegate of type D3, closed over a string, is created for the static method M2. 调用方法以显示它使用绑定的字符串。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!
' 

示例2Example 2

下面的代码示例演示参数类型和返回类型的兼容性。The following code example demonstrates compatibility of parameter types and return types.

备注

此代码示例使用CreateDelegate(Type, MethodInfo)方法重载。This code example uses the CreateDelegate(Type, MethodInfo) method overload. 使用采用MethodInfo的其他重载类似。The use of other overloads that take MethodInfo is similar.

此代码示例定义一个名为Base的基类和一个名为Derived的类Base,该类派生自。The code example defines a base class named Base and a class named Derived that derives from Base. 派生类具有一个名static MyMethodShared的(在 Visual Basic)方法,该方法具有Base一个类型为的Derived参数和一个返回类型。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. 此代码示例还定义了一个名Example为的委托,该委托Derived具有一个类型为的Base参数和一个返回类型。The code example also defines a delegate named Example that has one parameter of type Derived and a return type of Base.

此代码示例演示了可用于表示Example方法MyMethod的名为的委托。The code example demonstrates that the delegate named Example can be used to represent the method MyMethod. 方法可以绑定到委托,原因如下:The method can be bound to the delegate because:

  • 委托(Derived)的参数类型比MyMethodBase)的参数类型具有更强的限制,因此,将委托的参数传递给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.

  • MyMethodBase)的返回类型的限制性强于委托的参数类型(),因此,将方法的返回类型强制转换为委托的返回类型始终是安全的。DerivedThe 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.

此代码示例不生成输出。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

示例3Example 3

下面的代码示例演示一个委托类型可以表示的所有方法,并使用CreateDelegate方法来创建委托。The following code example shows all the methods a single delegate type can represent, using the CreateDelegate method to create the delegates.

备注

CreateDelegate方法有两个重载,它指定firstArgument和 a MethodInfo; 其功能相同,不同之处在于,它允许您指定是否要在绑定失败时引发,另一个始终引发。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. 此代码示例使用两个重载。This code example uses both overloads.

此代码示例定义了两个CF:和,以及一个D类型C为的参数的委托类型。The code example defines two classes, C and F, and a delegate type D with one argument of type C. 类具有匹配的静态和实例方法M1M3M4,并且类C还具有一个不带参数M2的实例方法。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.

第三个名Example为的类包含创建委托的代码。A third class named Example contains the code that creates the delegates.

  • 为类型M1 C和类型F的实例方法创建委托; 每个委托都在各自类型的实例上关闭。Delegates are created for instance method M1 of type C and type F; each is closed over an instance of the respective type. ID类型M1 为的方法显示绑定实例和C参数的属性。Method M1 of type C displays the ID properties of the bound instance and of the argument.

  • 为类型M2 C的方法创建委托。A delegate is created for method M2 of type C. 这是一个打开的实例委托,其中委托的参数表示实例方法上隐藏的第一个参数。This is an open instance delegate, in which the argument of the delegate represents the hidden first argument on the instance method. 方法没有其他参数。The method has no other arguments. 它被称为静态方法。It is called as if it were a static method.

  • 为类型M3 C和类型F的静态方法创建委托; 这些是开放式静态委托。Delegates are created for static method M3 of type C and type F; these are open static delegates.

  • 最后,为类型M4 C和类型F的静态方法创建委托; 每个方法都将声明类型作为其第一个参数,并提供类型的实例,因此这些委托在其第一个参数上关闭.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. ID类型M4 为的方法显示绑定实例和C参数的属性。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
'

注解

调用此方法重载等效于调用CreateDelegate(Type, Object, MethodInfo, Boolean)方法重载并为throwOnBindFailure指定trueCalling this method overload is equivalent to calling the CreateDelegate(Type, Object, MethodInfo, Boolean) method overload and specifying true for throwOnBindFailure. 这两个重载提供最灵活的方法来创建委托。These two overloads provide the most flexible way to create delegates. 您可以使用它们为静态方法或实例方法创建委托,还可以选择指定第一个参数。You can use them to create delegates for either static or instance methods, and optionally to specify the first argument.

备注

如果不提供第一个参数,请使用CreateDelegate(Type, MethodInfo)方法重载以获得更好的性能。If you do not supply a first argument, use the CreateDelegate(Type, MethodInfo) method overload for better performance.

委托类型和方法必须具有兼容的返回类型。The delegate type and the method must have compatible return types. 也就是说,的method返回类型必须可分配给的返回type类型。That is, the return type of method must be assignable to the return type of type.

如果firstArgument提供了,则每次调用method委托时将传递到该委托;firstArgument被称为绑定到委托,并且委托被称为通过其第一个参数关闭。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. 如果methodstaticmethod firstArgument在 Visual Basic),则调用委托时提供的自变量列表包含除第一个以外的所有参数; 如果为实例方法,则将传递给隐藏的实例Shared参数(由this中C#的表示, Me在 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).

如果firstArgument提供了,则的method第一个参数必须是引用类型,并且firstArgument必须与该类型兼容。If firstArgument is supplied, the first parameter of method must be a reference type, and firstArgument must be compatible with that type.

重要

如果methodfirstArgument ValueType Object (在 Visual Basic 中),并且其第一个参数的类型为或,则可以是值类型。Shared staticIf method is static (Shared in Visual Basic) and its first parameter is of type Object or ValueType, then firstArgument can be a value type. 在这种firstArgument情况下,会自动装箱。In this case firstArgument is automatically boxed. 对于任何其他参数,都不会出现自动装箱,这与在C#或 Visual Basic 函数调用中一样。Automatic boxing does not occur for any other arguments, as it would in a C# or Visual Basic function call.

如果firstArgument是 null 引用并且method是实例方法,则结果取决于委托类型type和的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:

  • 如果的type签名显式包含隐藏的method第一个参数,则称委托表示一个开放式实例方法。If the signature of type explicitly includes the hidden first parameter of method, the delegate is said to represent an open instance method. 调用委托时,将参数列表中的第一个自变量传递给的隐藏实例参数methodWhen the delegate is invoked, the first argument in the argument list is passed to the hidden instance parameter of method.

  • 如果methodtype匹配的签名(即所有参数类型都兼容),则将委托称为空引用。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. 调用委托类似于在 null 实例上调用实例方法,这并不是特别有用的操作。Invoking the delegate is like calling an instance method on a null instance, which is not a particularly useful thing to do.

如果firstArgument是 null 引用并且method是静态的,则结果取决于委托类型type和的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:

  • 如果methodtype匹配的签名(即,所有参数类型都兼容),则委托称为表示开放式静态方法。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. 这是静态方法最常见的情况。This is the most common case for static methods. 在这种情况下,可以使用CreateDelegate(Type, MethodInfo)方法重载获得略微更好的性能。In this case, you can get slightly better performance by using the CreateDelegate(Type, MethodInfo) method overload.

  • 如果的签名type以的第二个method参数开始,而其余的参数类型是兼容的,则认为该委托是通过空引用关闭的。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. 调用委托时,空引用将传递给的第一个参数methodWhen the delegate is invoked, a null reference is passed to the first parameter of method.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,此方法可用于访问非公共方法,前提是已使用标志授予调用方,而非公共方法的授予集限制为调用方的授予集或子集.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.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. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

兼容的参数类型和返回类型Compatible Parameter Types and Return Type

委托的参数类型和返回类型必须与委托表示的方法的参数类型和返回类型兼容;类型不必完全匹配。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.

备注

在 .NET Framework 版本1.0 和1.1 中,类型必须完全匹配。In the .NET Framework version 1.0 and 1.1, the types must match exactly.

如果委托参数的类型的限制性强于方法参数的类型,则该委托的参数与该方法的相应参数兼容,因为这可保证传递给委托的参数可以安全地传递给方法。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.

同样,如果方法的返回类型的限制性强于委托的返回类型,则该委托的返回类型与该方法的返回类型兼容,因为这可保证方法的返回值可以安全地强制转换为委托的返回类型。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.

例如,具有Hashtable类型为的参数和返回类型的Object委托可以表示具有类型Object的参数和类型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.

确定委托可以表示的方法Determining the Methods a Delegate Can Represent

考虑此重载CreateDelegate提供的灵活性的另一种有用方法是,任何给定的委托都可以表示方法签名和方法类型(静态与实例)的四种不同组合。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). 请考虑一个具有D类型C为的参数的委托类型。Consider a delegate type D with one argument of type C. 下面描述了方法可以D表示的方法,忽略返回类型,因为它在所有情况下都必须匹配:The following describes the methods D can represent, ignoring the return type since it must match in all cases:

  • D可以表示任何具有一个类型C为的参数的任何实例方法,而不考虑该实例方法所属的类型。D can represent any instance method that has exactly one argument of type C, regardless of what type the instance method belongs to. CreateDelegate调用时, firstArgument是该类型method的一个实例,而所生成的委托则被称为关闭该实例。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. (完全, D如果firstArgument为空引用,还可以通过空引用关闭。)(Trivially, D can also be closed over a null reference if firstArgument is a null reference.)

  • D可以表示没有参数的实例C方法。D can represent an instance method of C that has no arguments. 调用CreateDelegate时, firstArgument为空引用。When CreateDelegate is called, firstArgument is a null reference. 生成的委托表示开放式实例方法, C必须在每次调用时提供实例。The resulting delegate represents an open instance method, and an instance of C must be supplied each time it is invoked.

  • D可以表示静态方法,该方法采用一个类型C的参数,该方法可以属于任何类型。D can represent a static method that takes one argument of type C, and that method can belong to any type. 调用CreateDelegate时, firstArgument为空引用。When CreateDelegate is called, firstArgument is a null reference. 生成的委托表示开放式静态方法, C必须在每次调用时提供实例。The resulting delegate represents an open static method, and an instance of C must be supplied each time it is invoked.

  • D可以表示属于类型F且具有两个类型F为的参数和类型C的静态方法。D can represent a static method that belongs to type F and has two arguments, of type F and type C. CreateDelegate调用时, firstArgument是的F实例。When CreateDelegate is called, firstArgument is an instance of F. 生成的委托表示在该实例F上关闭的静态方法。The resulting delegate represents a static method that is closed over that instance of F. 请注意,在FC的类型相同的情况下,静态方法具有该类型的两个参数。Note that in the case where F and C are the same type, the static method has two arguments of that type. (在这种情况D下,如果firstArgument为 null 引用,则会通过空引用关闭。)(In this case, D is closed over a null reference if firstArgument is a null reference.)

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

CreateDelegate(Type, Type, String)

创建指定类型的委托,该委托表示指定类的指定静态方法。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

参数

type
Type

要创建的委托的 TypeThe Type of delegate to create.

target
Type

表示实现 method 的类的 TypeThe Type representing the class that implements method.

method
String

委托要表示的静态方法的名称。The name of the static method that the delegate is to represent.

返回

指定类型的委托,该委托表示指定类的指定静态方法。A delegate of the specified type that represents the specified static method of the specified class.

异常

typenulltype is null.

-or- targetnulltarget is null.

-or- methodnullmethod is null.

type 不继承 MulticastDelegatetype does not inherit MulticastDelegate.

- 或 --or- type 不是 RuntimeTypetype is not a RuntimeType. 请参阅反射中的运行时类型See Runtime Types in Reflection.

-or- target 不是 RuntimeTypetarget is not a RuntimeType.

- 或 --or- target 为开放式泛型类型。target is an open generic type. 也就是说,其 ContainsGenericParameters 属性为 trueThat is, its ContainsGenericParameters property is true.

- 或 --or- method 不是 static 方法(在 Visual Basic 中为 Shared 方法)。method is not a static method (Shared method in Visual Basic).

-or- 无法绑定 method,例如因为找不到它,并且 throwOnBindFailuretruemethod cannot be bound, for example because it cannot be found, and throwOnBindFailure is true.

找不到 typeInvoke 方法。The Invoke method of type is not found.

调用方没有访问 method 所必需的权限。The caller does not have the permissions necessary to access method.

注解

此方法仅为静态方法创建委托。This method creates delegates for static methods only. 实例方法是与类的实例关联的方法;静态方法是与类自身相关联的方法。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.

此方法重载等效于调用CreateDelegate(Type, Type, String, Boolean, Boolean)方法重载, ignoreCase并为指定falsetrue throwOnBindFailureThis method overload is equivalent to calling the CreateDelegate(Type, Type, String, Boolean, Boolean) method overload, specifying false for ignoreCase and true for throwOnBindFailure.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,此方法可用于访问非公共方法,前提是已使用标志授予调用方,而非公共方法的授予集限制为调用方的授予集或子集.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.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. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

CreateDelegate(Type, MethodInfo)

创建指定类型的委托以表示指定的静态方法。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

参数

type
Type

要创建的委托的 TypeThe Type of delegate to create.

method
MethodInfo

描述该委托要表示的静态或实例方法的 MethodInfoThe MethodInfo describing the static or instance method the delegate is to represent. .NET Framework 1.0 和 1.1 版中仅支持静态方法。Only static methods are supported in the .NET Framework version 1.0 and 1.1.

返回

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

异常

typenulltype is null.

-or- methodnullmethod is null.

type 不继承 MulticastDelegatetype does not inherit MulticastDelegate.

- 或 --or- type 不是 RuntimeTypetype is not a RuntimeType. 请参阅反射中的运行时类型See Runtime Types in Reflection.

- 或 --or- method 不是一种静态方法,并且 .NET Framework 版本为 1.0 或 1.1。method is not a static method, and the .NET Framework version is 1.0 or 1.1.

-or- 无法绑定 methodmethod cannot be bound.

-or- method 不是 RuntimeMethodInfomethod is not a RuntimeMethodInfo. 请参阅反射中的运行时类型See Runtime Types in Reflection.

找不到 typeInvoke 方法。The Invoke method of type is not found.

调用方没有访问 method 所必需的权限。The caller does not have the permissions necessary to access method.

示例

本部分包含两个代码示例。This section contains two code examples. 第一个示例演示可使用此方法重载创建的两种委托:通过实例方法打开并通过静态方法打开。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.

第二个代码示例演示兼容的参数类型和返回类型。The second code example demonstrates compatible parameter types and return types.

示例1Example 1

下面的代码示例演示了使用此CreateDelegate方法重载可以创建委托的两种方法。The following code example demonstrates the two ways a delegate can be created using this overload of the CreateDelegate method.

备注

CreateDelegate方法有两个重载,它MethodInfo指定但不指定第一个参数; 其功能是相同的,但前者允许您指定是否要在绑定失败时引发,另一个始终引发。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. 此代码示例使用两个重载。This code example uses both overloads.

该示例使用静态方法C M2 、实例方法M1C两个委托类型来声明类: D1使用实例和字符串,并D2使用字符串。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.

名为Example的第二个类包含创建委托的代码。A second class named Example contains the code that creates the delegates.

  • 为实例方法M1创建D1表示开放式实例方法的类型为的委托。A delegate of type D1, representing an open instance method, is created for the instance method M1. 调用委托时,必须传递一个实例。An instance must be passed when the delegate is invoked.

  • 为静态方法M2创建D2一个表示 open 静态方法的类型的委托。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!
' 

示例2Example 2

下面的代码示例演示参数类型和返回类型的兼容性。The following code example demonstrates compatibility of parameter types and return types.

此代码示例定义一个名为Base的基类和一个名为Derived的类Base,该类派生自。The code example defines a base class named Base and a class named Derived that derives from Base. 派生类具有一个名static MyMethodShared的(在 Visual Basic)方法,该方法具有Base一个类型为的Derived参数和一个返回类型。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. 此代码示例还定义了一个名Example为的委托,该委托Derived具有一个类型为的Base参数和一个返回类型。The code example also defines a delegate named Example that has one parameter of type Derived and a return type of Base.

此代码示例演示了可用于表示Example方法MyMethod的名为的委托。The code example demonstrates that the delegate named Example can be used to represent the method MyMethod. 方法可以绑定到委托,原因如下:The method can be bound to the delegate because:

  • 委托(Derived)的参数类型比MyMethodBase)的参数类型具有更强的限制,因此,将委托的参数传递给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.

  • MyMethodBase)的返回类型的限制性强于委托的参数类型(),因此,将方法的返回类型强制转换为委托的返回类型始终是安全的。DerivedThe 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.

此代码示例不生成输出。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

注解

在 .NET Framework 版本1.0 和1.1 中,此方法重载仅为静态方法创建委托。In the .NET Framework version 1.0 and 1.1, this method overload creates delegates for static methods only. 在 .NET Framework 版本2.0 中,此方法重载还可以创建开放式实例方法委托;也就是说,显式提供实例方法的隐藏第一个参数的委托。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. 有关详细说明,请参阅更通用CreateDelegate(Type, Object, MethodInfo)的方法重载,该重载允许您为实例或静态方法创建开放或关闭委托的所有组合,还可以选择指定第一个参数。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.

备注

如果委托未通过其第一个参数关闭,则应使用此方法重载,因为在这种情况下,该委托的速度稍快。This method overload should be used when the delegate is not closed over its first argument, because it is somewhat faster in that case.

此方法重载等效于调用CreateDelegate(Type, MethodInfo, Boolean)方法重载,并为throwOnBindFailure指定trueThis method overload is equivalent to calling the CreateDelegate(Type, MethodInfo, Boolean) method overload and specifying true for throwOnBindFailure.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,此方法可用于访问非公共方法,前提是已使用标志授予调用方,而非公共方法的授予集限制为调用方的授予集或子集.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.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. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

兼容的参数类型和返回类型Compatible Parameter Types and Return Type

在 .NET Framework 版本2.0 中,使用此方法重载创建的委托的参数类型和返回类型必须与委托表示的方法的参数类型和返回类型兼容;类型不必完全匹配。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. 这表示 .NET Framework 版本1.0 和1.1 中绑定行为的 relaxation,其中类型必须完全匹配。This represents a relaxation of the binding behavior in the .NET Framework version 1.0 and 1.1, where the types must match exactly.

如果委托参数的类型的限制性强于方法参数的类型,则该委托的参数与该方法的相应参数兼容,因为这可保证传递给委托的参数可以安全地传递给方法。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.

同样,如果方法的返回类型的限制性强于委托的返回类型,则该委托的返回类型与该方法的返回类型兼容,因为这可保证方法的返回值可以安全地强制转换为委托的返回类型。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.

例如,具有Hashtable类型为的参数和返回类型的Object委托可以表示具有类型Object的参数和类型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.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

适用于