Delegate.CreateDelegate メソッド

定義

指定した型のデリゲートを作成します。

オーバーロード

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

大文字と小文字の区別方法およびバインドに失敗したときの動作を指定して、指定したクラスの指定した静的メソッドを表す、指定した型のデリゲートを作成します。

CreateDelegate(Type, Type, String, Boolean)

指定したクラスの指定した静的メソッドを表す、指定した型のデリゲートを、大文字と小文字の区別方法を指定して作成します。

CreateDelegate(Type, Object, String, Boolean)

大文字と小文字の区別方法を指定して、指定したクラス インスタンスに対して呼び出す指定した型のデリゲートを作成します。

CreateDelegate(Type, Object, MethodInfo, Boolean)

指定された静的メソッドまたはインスタンス メソッドを表す、指定した型のデリゲートを、第 1 引数およびバインドに失敗したときの動作を指定して作成します。

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

大文字と小文字の区別方法およびバインドに失敗したときの動作を指定して、指定したクラス インスタンスに対して呼び出す指定した型のデリゲートを作成します。

CreateDelegate(Type, MethodInfo, Boolean)

指定された静的メソッドを表す、指定された型のデリゲートを、バインドに失敗した場合の動作を指定して作成します。

CreateDelegate(Type, Object, String)

指定したクラス インスタンスに対して呼び出す指定したインスタンス メソッドを表す、指定した型のデリゲートを作成します。

CreateDelegate(Type, Object, MethodInfo)

指定された静的メソッドまたはインスタンス メソッドを表す、指定した型のデリゲートを、第 1 引数を指定して作成します。

CreateDelegate(Type, Type, String)

指定したクラスの指定した静的メソッドを表す、指定した型のデリゲートを作成します。

CreateDelegate(Type, MethodInfo)

指定したメソッドを表す、指定した型のデリゲートを作成します。

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

大文字と小文字の区別方法およびバインドに失敗したときの動作を指定して、指定したクラスの指定した静的メソッドを表す、指定した型のデリゲートを作成します。

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);
public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure);
static member CreateDelegate : Type * Type * string * bool * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Type, method As String, ignoreCase As Boolean, throwOnBindFailure As Boolean) As Delegate

パラメーター

type
Type

作成するデリゲートの Type

target
Type

method を実装するクラスを表す Type

method
String

デリゲートによって表される静的メソッドの名前。

ignoreCase
Boolean

メソッドの名前を比較するとき大文字と小文字を無視するかどうかを示すブール値。

throwOnBindFailure
Boolean

method をバインドできないときに例外をスローする場合は true。それ以外の場合は false

戻り値

指定したクラスの指定した静的メソッドを表す、指定した型のデリゲート。

例外

typenullです。

または

targetnullです。

または

methodnullです。

typeMulticastDelegate を継承しません。

- または -

typeRuntimeType ではありません。 「リフレクションのランタイム型」を参照してください。

- または -

targetRuntimeType ではありません。

- または -

target はオープン ジェネリック型です。 つまり、その ContainsGenericParameters プロパティは true です。

- または -

methodstatic メソッド (Visual Basic では Shared メソッド) ではありません。

- または -

見つからないなどの原因により、method をバインドできません。また、throwOnBindFailuretrue です。

typeInvoke メソッドが見つかりません。

method へのアクセスに必要なアクセス許可が呼び出し元にありません。

注釈

このメソッドは、静的メソッドのデリゲートのみを作成します。 インスタンス メソッドは、 クラスのインスタンスに関連付けられているメソッドです。静的メソッドは、クラス自体に関連付けられているメソッドです。

Note

.NET Framework 2.0 Service Pack 1 以降では、このメソッドを使用して、フラグを使用して呼び出し元が許可ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccessされている場合、および非パブリック メソッドの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合は、非パブリック メソッドにアクセスできます。 ( リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。

この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

こちらもご覧ください

適用対象

CreateDelegate(Type, Type, String, Boolean)

指定したクラスの指定した静的メソッドを表す、指定した型のデリゲートを、大文字と小文字の区別方法を指定して作成します。

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
Public Shared Function CreateDelegate (type As Type, target As Type, method As String, ignoreCase As Boolean) As Delegate

パラメーター

type
Type

作成するデリゲートの Type

target
Type

method を実装するクラスを表す Type

method
String

デリゲートによって表される静的メソッドの名前。

ignoreCase
Boolean

メソッドの名前を比較するとき大文字と小文字を無視するかどうかを示すブール値。

戻り値

指定したクラスの指定した静的メソッドを表す、指定した型のデリゲート。

例外

typenullです。

または

targetnullです。

または

methodnullです。

typeMulticastDelegate を継承しません。

- または -

typeRuntimeType ではありません。 「リフレクションのランタイム型」を参照してください。

- または -

targetRuntimeType ではありません。

- または -

target はオープン ジェネリック型です。 つまり、その ContainsGenericParameters プロパティは true です。

- または -

methodstatic メソッド (Visual Basic では Shared メソッド) ではありません。

- または -

method をバインドできません (たとえば、これが見つからないなど)。

typeInvoke メソッドが見つかりません。

method へのアクセスに必要なアクセス許可が呼び出し元にありません。

注釈

このメソッドは、静的メソッドのデリゲートのみを作成します。 インスタンス メソッドは、 クラスのインスタンスに関連付けられているメソッドです。静的メソッドは、クラス自体に関連付けられているメソッドです。

このメソッド オーバーロードは、 を指定して メソッド オーバーロードをCreateDelegate(Type, Type, String, Boolean, Boolean)呼び出すことtruethrowOnBindFailureと同じです。

Note

.NET Framework 2.0 Service Pack 1 以降では、このメソッドを使用して、フラグを使用して呼び出し元が許可ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccessされている場合、および非パブリック メソッドの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合は、非パブリック メソッドにアクセスできます。 ( リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。

この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

こちらもご覧ください

適用対象

CreateDelegate(Type, Object, String, Boolean)

大文字と小文字の区別方法を指定して、指定したクラス インスタンスに対して呼び出す指定した型のデリゲートを作成します。

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
Public Shared Function CreateDelegate (type As Type, target As Object, method As String, ignoreCase As Boolean) As Delegate

パラメーター

type
Type

作成するデリゲートの Type

target
Object

method を呼び出す対象のクラス インスタンス。

method
String

デリゲートによって表されるインスタンス メソッドの名前。

ignoreCase
Boolean

メソッドの名前を比較するとき大文字と小文字を無視するかどうかを示すブール値。

戻り値

指定したクラス インスタンスに対して呼び出す指定したインスタンス メソッドを表す、指定した型のデリゲート。

例外

typenullです。

または

targetnullです。

または

methodnullです。

typeMulticastDelegate を継承しません。

- または -

typeRuntimeType ではありません。 「リフレクションのランタイム型」を参照してください。

- または -

method はインスタンス メソッドではありません。

- または -

method をバインドできません (たとえば、これが見つからないなど)。

typeInvoke メソッドが見つかりません。

method へのアクセスに必要なアクセス許可が呼び出し元にありません。

注釈

このメソッドは、インスタンス メソッドのデリゲートのみを作成します。 インスタンス メソッドは、 クラスのインスタンスに関連付けられているメソッドです。静的メソッドは、クラス自体に関連付けられているメソッドです。

このメソッド オーバーロードは、 を指定して メソッド オーバーロードをCreateDelegate(Type, Object, String, Boolean, Boolean)呼び出すことtruethrowOnBindFailureと同じです。

Note

.NET Framework 2.0 Service Pack 1 以降では、このメソッドを使用して、フラグを使用して呼び出し元が許可ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccessされている場合、および非パブリック メソッドの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合は、非パブリック メソッドにアクセスできます。 ( リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。

この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

こちらもご覧ください

適用対象

CreateDelegate(Type, Object, MethodInfo, Boolean)

指定された静的メソッドまたはインスタンス メソッドを表す、指定した型のデリゲートを、第 1 引数およびバインドに失敗したときの動作を指定して作成します。

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);
public static Delegate CreateDelegate (Type type, object firstArgument, System.Reflection.MethodInfo method, bool throwOnBindFailure);
static member CreateDelegate : Type * obj * System.Reflection.MethodInfo * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, firstArgument As Object, method As MethodInfo, throwOnBindFailure As Boolean) As Delegate

パラメーター

type
Type

作成するデリゲートの型を表す Type

firstArgument
Object

デリゲートが表すメソッドの第 1 引数である Object。 インスタンス メソッドの場合は、そのインスタンスの型との互換性が必要です。

method
MethodInfo

デリゲートが表す静的メソッドまたはインスタンス メソッドの情報を記述する MethodInfo

throwOnBindFailure
Boolean

method をバインドできないときに例外をスローする場合は true。それ以外の場合は false

戻り値

指定された静的メソッドまたはインスタンス メソッドを表す、指定された型のデリゲート。throwOnBindFailurefalse で、デリゲートを method にバインドできない場合は null

例外

typenullです。

または

methodnullです。

typeMulticastDelegate を継承しません。

- または -

typeRuntimeType ではありません。 「リフレクションのランタイム型」を参照してください。

- または -

method はバインドできず、throwOnBindFailuretrue です。

- または -

methodRuntimeMethodInfo ではありません。 「リフレクションのランタイム型」を参照してください。

typeInvoke メソッドが見つかりません。

method へのアクセスに必要なアクセス許可が呼び出し元にありません。

このセクションには、3 つのコード例が含まれています。 最初の例では、作成できるデリゲートの 4 種類を示します。インスタンス メソッドで閉じる、インスタンス メソッドで開く、静的メソッドで開く、静的メソッドで閉じるなどです。

2 番目のコード例では、互換性のあるパラメーター型と戻り値の型を示します。

3 番目のコード例では、1 つのデリゲート型を定義し、デリゲート型が表すことができるすべてのメソッドを示します。

例 1

次のコード例では、 メソッドのこのオーバーロードを使用してデリゲートを作成する 4 つの方法を CreateDelegate 示します。

Note

MethodInfoCreateDelegate指定firstArgumentする メソッドには 2 つのオーバーロードがあります。その機能は同じですが、1 つはバインドに失敗した場合にスローするかどうかを指定でき、もう 1 つは常に スローします。 このコード例では、両方のオーバーロードを使用します。

この例では、静的メソッドとインスタンス メソッド を使用して クラスCを宣言し、次の C 3 つのデリゲート型D1を宣言します。 のインスタンスと文字列を受け取り、D2文字列を受け取り、D3引数がありません。M2M1

という名前 Example の 2 番目のクラスには、デリゲートを作成するコードが含まれています。

  • のインスタンスで閉じられている 型 D2Cデリゲートが、インスタンス メソッド M1に対して作成されます。 バインドされた インスタンス C が常に使用されることを示すために、異なる文字列で呼び出されます。

  • インスタンス メソッド M1に対して、開いているインスタンス メソッドを表す 型D1のデリゲートが作成されます。 デリゲートの呼び出し時にインスタンスを渡す必要があります。

  • 静的メソッド M2に対して、開いている静的メソッドを表す 型D2のデリゲートが作成されます。

  • 最後に、静的メソッド M2に対して、文字列で閉じられている 型D3のデリゲートが作成されます。 メソッドは、バインドされた文字列を使用することを示すために呼び出されます。

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!
 */
open System
open System.Reflection

// A sample class with an instance method and a static method.
type C(id) =
    member _.M1(s) =
        printfn $"Instance method M1 on C:  id = %i{id}, s = %s{s}"

    static member M2(s) =
        printfn $"Static method M2 on C:  s = %s{s}"
    
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit

let c1 = C 42

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

printfn "\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.
let 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 then
    let d2 = test :?> D2

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

printfn "\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.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1

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

printfn "\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.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2

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

printfn "\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.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3

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

// 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!
'

例 2

次のコード例は、パラメーター型と戻り値の型の互換性を示しています。

Note

このコード例では、 メソッドのオーバーロードを CreateDelegate(Type, MethodInfo) 使用します。 受け取る MethodInfo 他のオーバーロードの使用も同様です。

このコード例では、 という名前Baseの基底クラスと からBase派生する という名前Derivedのクラスを定義しています。 派生クラスには、 型のパラメーターを static 1 つ、戻り値の型Baseを持つ という名前MyMethodの (Shared Visual Basic の場合) メソッドがありますDerived。 このコード例では、 型のパラメーターが 1 つ、戻り値の型Derivedが の という名前ExampleBaseデリゲートも定義しています。

このコード例では、 という名前 Example のデリゲートを使用して メソッド MyMethodを表すことができることを示します。 メソッドは、次の理由でデリゲートにバインドできます。

  • デリゲート () のパラメーター型は、Derived() のパラメーター型よりも制限が厳しいため、デリゲートのMyMethodBase引数を に渡しても常にMyMethod安全です。

  • (Derived) の戻り値のMyMethod型は、デリゲート (Base) のパラメーター型よりも制限が厳しいため、メソッドの戻り値の型をデリゲートの戻り値の型にキャストしても常に安全です。

このコード例では、出力は生成されません。

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());
    }
}
open System
open System.Reflection

// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end

type Derived() =
    inherit 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.
    static member MyMethod(arg: Base) =
        Derived()

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base

// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static

// Get a MethodInfo that represents MyMethod.
let 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).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example

// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
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

例 3

次のコード例は、1 つのデリゲート型が表すことができるすべてのメソッドを示しています。

Note

MethodInfoCreateDelegate指定firstArgumentする メソッドには 2 つのオーバーロードがあります。その機能は同じですが、1 つはバインドに失敗した場合にスローするかどうかを指定でき、もう 1 つは常に スローします。 このコード例では、両方のオーバーロードを使用します。

このコード例では、 と の 2 つのクラスとFCDの 1 つの引数を持つデリゲート型を定義していますC。 クラスには、一致する静的メソッドとインスタンス メソッド M1M3、および M4クラス C があり、引数を持たないインスタンス メソッド M2 もあります。

という名前 Example の 3 番目のクラスには、デリゲートを作成するコードが含まれています。

  • デリゲートは、型と型CFのインスタンス メソッドM1に対して作成されます。各デリゲートは、それぞれの型のインスタンスで閉じられます。 型Cの メソッドM1は、IDバインドされたインスタンスのプロパティと 引数のプロパティを表示します。

  • Cの メソッドM2に対してデリゲートが作成されます。 これは、デリゲートの引数がインスタンス メソッドの非表示の最初の引数を表す、開いているインスタンス デリゲートです。 メソッドには他の引数はありません。

  • デリゲートは、型と型CFの静的メソッドM3に対して作成されます。これらは、開いている静的デリゲートです。

  • 最後に、型と型CFの静的メソッドM4に対してデリゲートが作成されます。各メソッドは、宣言する型を最初の引数として持ち、型のインスタンスが指定されるため、デリゲートは最初の引数で閉じられます。 型Cの メソッドM4は、IDバインドされたインスタンスのプロパティと 引数のプロパティを表示します。

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
*/
open System

// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
type C(id) =
    member _.ID = id 

    member _.M1(c: C) =
        printfn $"Instance method M1(C c) on C:  this.id = {id}, c.ID = {c.ID}"

    member _.M2() =
        printfn $"Instance method M2() on C:  this.id = {id}"

    static member M3(c: C) =
        printfn $"Static method M3(C c) on C:  c.ID = {c.ID}"

    static member M4(c1: C, c2: C) =
        printfn $"Static method M4(C c1, C c2) on C:  c1.ID = {c1.ID}, c2.ID = {c2.ID}"

// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
type D = delegate of C -> unit


type F() =
    member _.M1(c: C) =
        printfn $"Instance method M1(C c) on F:  c.ID = {c.ID}"

    member _.M3(c: C) =
        printfn $"Static method M3(C c) on F:  c.ID = {c.ID}"

    member _.M4(f: F, c: C) =
        printfn $"Static method M4(F f, C c) on F:  c.ID = {c.ID}"

[<EntryPoint>]
let main _ =
    let c1 = C 42
    let c2 = C 1491
    let f1 = F()

    // Instance method with one argument of type C.
    let cmi1 = typeof<C>.GetMethod "M1"
    // Instance method with no arguments.
    let cmi2 = typeof<C>.GetMethod "M2"
    // Static method with one argument of type C.
    let cmi3 = typeof<C>.GetMethod "M3"
    // Static method with two arguments of type C.
    let cmi4 = typeof<C>.GetMethod "M4"

    // Instance method with one argument of type C.
    let fmi1 = typeof<F>.GetMethod "M1"
    // Static method with one argument of type C.
    let fmi3 = typeof<F>.GetMethod "M3"
    // Static method with an argument of type F and an argument
    // of type C.
    let fmi4 = typeof<F>.GetMethod "M4"

    printfn "\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.
    let d = Delegate.CreateDelegate(typeof<D>, c1, cmi1) :?> D
    d.Invoke c2
    let d =  Delegate.CreateDelegate(typeof<D>, f1, fmi1) :?> D
    d.Invoke 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.
    let d = Delegate.CreateDelegate(typeof<D>, null, cmi2) :?> D
    d.Invoke c1

    printfn "\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.
    let d = Delegate.CreateDelegate(typeof<D>, null, cmi3) :?> D
    d.Invoke c1
    let d = Delegate.CreateDelegate(typeof<D>, null, fmi3) :?> D
    d.Invoke c1

    printfn "\nA static method on any type, with an argument of"
    printfn "    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.
    let d = Delegate.CreateDelegate(typeof<D>, c1, cmi4) :?> D
    d.Invoke c2
    let 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).
    match test with
    | :? D as d ->
        d.Invoke c2
    | _ -> ()
    0

// 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) メソッドオーバーロードは、バインドに失敗すると常にスローされ、デリゲートを作成する最も柔軟な方法を提供します。 これらを使用して、最初の引数の有無にかかわらず、静的メソッドまたはインスタンス メソッドのデリゲートを作成できます。

Note

最初の引数を指定しない場合は、パフォーマンスを CreateDelegate(Type, MethodInfo, Boolean) 向上させるために メソッド オーバーロードを使用します。

デリゲート型と メソッドには、互換性のある戻り値の型が必要です。 つまり、 の戻り値の型は、 の method 戻り値の type型に割り当て可能である必要があります。

が指定されている場合firstArgumentは、デリゲートが呼び出firstArgumentされるたびに にmethod渡されます。これはデリゲートにバインドされると言われ、デリゲートは最初の引数で閉じられると言われます。 が static ( Visual Basic の場合) の場合method、デリゲートの呼び出し時に指定された引数リストには、最初の パラメーターを除くすべてのパラメーターが含まれます。が インスタンス メソッドの場合methodは、firstArgument非表示のインスタンス パラメーター (C#で、または Visual Basic では によってMe表されますthis) に渡Sharedされます。

が指定されている場合 firstArgument 、 の最初の method パラメーターは参照型であり、その型と firstArgument 互換性がある必要があります。

重要

static (Shared Visual Basic の場合) で、最初のパラメーターが 型Objectまたは ValueTypeの場合methodは、firstArgument値型にすることができます。 この場合 firstArgument は、自動的にボックス化されます。 自動ボックス化は、C# または Visual Basic 関数呼び出しの場合と同様に、他の引数には発生しません。

が null 参照でmethodインスタンス メソッドの場合firstArgument、結果はデリゲート型typeの シグネチャと のmethodシグネチャによって異なります。

  • のシグネチャ type に の非表示の最初の methodパラメーターが明示的に含まれている場合、デリゲートは開いているインスタンス メソッドを表すと言われます。 デリゲートが呼び出されると、引数リストの最初の引数が の非表示のインスタンス パラメーター methodに渡されます。

  • type のシグネチャが一致するmethod場合 (つまり、すべてのパラメーター型に互換性があります)、デリゲートは null 参照で閉じられると言われます。 デリゲートの呼び出しは、null インスタンスでインスタンス メソッドを呼び出すようなものです。これは特に便利な操作ではありません。

が null 参照でmethod静的な場合firstArgument、結果はデリゲート型typemethodのシグネチャに依存します。

  • type のシグネチャmethodが一致する場合 (つまり、すべてのパラメーター型に互換性があります)、デリゲートはオープン静的メソッドを表すと言います。 これは、静的メソッドの最も一般的なケースです。 この場合、 メソッドのオーバーロードを使用すると、パフォーマンスを CreateDelegate(Type, MethodInfo, Boolean) 若干向上させることができます。

  • のシグネチャ type が の 2 番目の method パラメーターで始まり、残りのパラメーター型に互換性がある場合、デリゲートは null 参照で閉じられると言われます。 デリゲートが呼び出されると、 の最初のパラメーター methodに null 参照が渡されます。

Note

.NET Framework 2.0 Service Pack 1 以降では、このメソッドを使用して、フラグを使用して呼び出し元が許可ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccessされている場合、および非パブリック メソッドの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合は、非パブリック メソッドにアクセスできます。 ( リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。

この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

互換性のあるパラメーター型と戻り値の型

デリゲートのパラメーター型と戻り値の型は、デリゲートが表すメソッドのパラメーター型と戻り値の型と互換性がある必要があります。型は正確に一致する必要はありません。

デリゲートのパラメーターにメソッドのパラメーターよりも限定的な型が指定された場合、両者のパラメーター間に型の互換性があると見なされます。これによって、デリゲートに渡された引数が、メソッドに対して安全に渡されることが保証されます。

同様に、メソッドの戻り値の型の制限がデリゲートの戻り値の型より多いと、メソッドの戻り値がデリゲートの戻り値の型に安全にキャストされることが保証されるため、デリゲートの戻り値の型とメソッドの戻り値の型には互換性があります。

たとえば、 型のパラメーターと 戻り値の型HashtableObjectを持つデリゲートは、 型のパラメーターと 型ObjectHashtable戻り値を持つメソッドを表すことができます。

デリゲートが表すことができるメソッドの決定

この オーバーロードによって提供される柔軟性を考えるもう 1 つの便利な方法は、任意の CreateDelegate デリゲートがメソッド シグネチャとメソッドの種類 (静的とインスタンス) の 4 つの異なる組み合わせを表すことができるということです。 型の 1 つの引数を持つデリゲート DCを考えてみましょう。 次に、すべてのケースで一致する D 必要があるため、戻り値の型を無視して、 を表すことができるメソッドについて説明します。

  • D は、インスタンス メソッドが属している型に関係なく、 型 Cの引数を 1 つだけ持つ任意のインスタンス メソッドを表すことができます。 が呼び出されると CreateDelegatefirstArgument は 型 method のインスタンスが属し、結果のデリゲートはそのインスタンスを介して閉じられると言われます。 (単純に、 D が の場合firstArgumentnullは null 参照で閉じることもできます)。

  • D は、引数を持たない の C インスタンス メソッドを表すことができます。 が呼び出されると CreateDelegatefirstArgument は null 参照です。 結果のデリゲートは開いているインスタンス メソッドを表し、 の C インスタンスは呼び出されるたびに指定する必要があります。

  • D は、 型 Cの 1 つの引数を受け取る静的メソッドを表し、そのメソッドは任意の型に属することができます。 が呼び出されると CreateDelegatefirstArgument は null 参照です。 結果のデリゲートは開いている静的メソッドを表し、 の C インスタンスは呼び出されるたびに指定する必要があります。

  • Dは、型に属し、型とCFF 2 つの引数を持つ静的メソッドを表すことができます。 が呼び出されると CreateDelegatefirstArgument は の Fインスタンスです。 結果のデリゲートは、 のそのインスタンス Fで閉じられている静的メソッドを表します。 と CF同じ型の場合、静的メソッドにはその型の 2 つの引数があることに注意してください。 (この場合、 D が の場合firstArgumentnullは null 参照で閉じられます)。

こちらもご覧ください

適用対象

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

大文字と小文字の区別方法およびバインドに失敗したときの動作を指定して、指定したクラス インスタンスに対して呼び出す指定した型のデリゲートを作成します。

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);
public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure);
static member CreateDelegate : Type * obj * string * bool * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Object, method As String, ignoreCase As Boolean, throwOnBindFailure As Boolean) As Delegate

パラメーター

type
Type

作成するデリゲートの Type

target
Object

method を呼び出す対象のクラス インスタンス。

method
String

デリゲートによって表されるインスタンス メソッドの名前。

ignoreCase
Boolean

メソッドの名前を比較するとき大文字と小文字を無視するかどうかを示すブール値。

throwOnBindFailure
Boolean

method をバインドできないときに例外をスローする場合は true。それ以外の場合は false

戻り値

指定したクラス インスタンスに対して呼び出す指定したインスタンス メソッドを表す、指定した型のデリゲート。

例外

typenullです。

または

targetnullです。

または

methodnullです。

typeMulticastDelegate を継承しません。

- または -

typeRuntimeType ではありません。 「リフレクションのランタイム型」を参照してください。

- または -

method はインスタンス メソッドではありません。

- または -

見つからないなどの原因により、method をバインドできません。また、throwOnBindFailuretrue です。

typeInvoke メソッドが見つかりません。

method へのアクセスに必要なアクセス許可が呼び出し元にありません。

注釈

このメソッドは、インスタンス メソッドのデリゲートのみを作成します。 インスタンス メソッドは、 クラスのインスタンスに関連付けられているメソッドです。静的メソッドは、クラス自体に関連付けられているメソッドです。

Note

.NET Framework 2.0 Service Pack 1 以降では、このメソッドを使用して、フラグを使用して呼び出し元が許可ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccessされている場合、および非パブリック メソッドの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合は、非パブリック メソッドにアクセスできます。 ( リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。

この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

こちらもご覧ください

適用対象

CreateDelegate(Type, MethodInfo, Boolean)

指定された静的メソッドを表す、指定された型のデリゲートを、バインドに失敗した場合の動作を指定して作成します。

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Reflection::MethodInfo ^ method, bool throwOnBindFailure);
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
Public Shared Function CreateDelegate (type As Type, method As MethodInfo, throwOnBindFailure As Boolean) As Delegate

パラメーター

type
Type

作成するデリゲートの Type

method
MethodInfo

デリゲートが表す静的メソッドまたはインスタンス メソッドの情報を記述する MethodInfo

throwOnBindFailure
Boolean

method をバインドできないときに例外をスローする場合は true。それ以外の場合は false

戻り値

指定した静的メソッドを表すための、指定した型のデリゲート。

例外

typenullです。

または

methodnullです。

typeMulticastDelegate を継承しません。

- または -

typeRuntimeType ではありません。 「リフレクションのランタイム型」を参照してください。

- または -

method はバインドできず、throwOnBindFailuretrue です。

- または -

methodRuntimeMethodInfo ではありません。 「リフレクションのランタイム型」を参照してください。

typeInvoke メソッドが見つかりません。

method へのアクセスに必要なアクセス許可が呼び出し元にありません。

このセクションには、2 つのコード例が含まれています。 最初の例では、このメソッド オーバーロードを使用して作成できる 2 種類のデリゲートを示します。インスタンス メソッドで開き、静的メソッドで開きます。

2 番目のコード例では、互換性のあるパラメーター型と戻り値の型を示します。

例 1

次のコード例では、 メソッドのこのオーバーロードを使用してデリゲートを作成する 2 つの方法を CreateDelegate 示します。

Note

メソッドには、最初の CreateDelegate 引数ではなく を MethodInfo 指定する 2 つのオーバーロードがあります。その機能は同じですが、1 つはバインドに失敗した場合にスローするかどうかを指定でき、もう 1 つは常にスローします。 このコード例では、両方のオーバーロードを使用します。

この例では、静的メソッドとインスタンス メソッド を使用して クラスCを宣言し、次の 2 つのデリゲート型を宣言します。 D1 は のCインスタンスと文字列を受け取り、D2文字列を受け取ります。M2M1

という名前 Example の 2 番目のクラスには、デリゲートを作成するコードが含まれています。

  • インスタンス メソッド M1に対して、開いているインスタンス メソッドを表す 型D1のデリゲートが作成されます。 デリゲートの呼び出し時にインスタンスを渡す必要があります。

  • 静的メソッド M2に対して、開いている静的メソッドを表す 型D2のデリゲートが作成されます。

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!
 */
open System
open System.Reflection

// A sample class with an instance method and a static method.
type C(id) =
    member _.M1(s) =
        printfn $"Instance method M1 on C:  id = %i{id}, s = %s{s}"

    static member M2(s) =
        printfn $"Static method M2 on C:  s = %s{s}"
    
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit

let c1 = C 42

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

printfn "\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.
let 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 then
    let d2 = test :?> D2

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

printfn "\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.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1

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

printfn "\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.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2

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

printfn "\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.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3

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

// 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!
'

例 2

次のコード例は、パラメーター型と戻り値の型の互換性を示しています。

Note

このコード例では、 メソッドのオーバーロードを CreateDelegate(Type, MethodInfo) 使用します。 受け取る MethodInfo 他のオーバーロードの使用も同様です。

このコード例では、 という名前Baseの基底クラスと からBase派生する という名前Derivedのクラスを定義しています。 派生クラスには、 型のパラメーターを static 1 つ、戻り値の型Baseを持つ という名前MyMethodの (Shared Visual Basic の場合) メソッドがありますDerived。 このコード例では、 型のパラメーターが 1 つ、戻り値の型Derivedが の という名前ExampleBaseデリゲートも定義しています。

このコード例では、 という名前 Example のデリゲートを使用して メソッド MyMethodを表すことができることを示します。 メソッドは、次の理由でデリゲートにバインドできます。

  • デリゲート () のパラメーター型は、Derived() のパラメーター型よりも制限が厳しいため、デリゲートのMyMethodBase引数を に渡しても常にMyMethod安全です。

  • (Derived) の戻り値のMyMethod型は、デリゲート (Base) のパラメーター型よりも制限が厳しいため、メソッドの戻り値の型をデリゲートの戻り値の型にキャストしても常に安全です。

このコード例では、出力は生成されません。

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());
    }
}
open System
open System.Reflection

// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end

type Derived() =
    inherit 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.
    static member MyMethod(arg: Base) =
        Derived()

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base

// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static

// Get a MethodInfo that represents MyMethod.
let 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).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example

// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
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

注釈

このメソッド オーバーロードでは、オープン静的メソッド デリゲートとオープン インスタンス メソッド デリゲート (インスタンス メソッドの非表示の最初の引数を公開するデリゲート) を作成できます。 詳細な説明については、より一般的な CreateDelegate(Type, Object, MethodInfo, Boolean) メソッド オーバーロードを参照してください。これにより、インスタンスメソッドまたは静的メソッドのオープンデリゲートまたはクローズデリゲートのすべての組み合わせを作成できます。

Note

このメソッド のオーバーロードは、デリゲートが最初の引数で閉じられない場合に使用する必要があります。その場合はやや高速であるためです。

Note

.NET Framework 2.0 Service Pack 1 以降では、このメソッドを使用して、フラグを使用して呼び出し元が許可ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccessされている場合、および非パブリック メソッドの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合は、非パブリック メソッドにアクセスできます。 ( リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。

この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

互換性のあるパラメーター型と戻り値の型

デリゲートのパラメーター型と戻り値の型は、デリゲートが表すメソッドのパラメーター型と戻り値の型と互換性がある必要があります。型は正確に一致する必要はありません。

デリゲートのパラメーターにメソッドのパラメーターよりも限定的な型が指定された場合、両者のパラメーター間に型の互換性があると見なされます。これによって、デリゲートに渡された引数が、メソッドに対して安全に渡されることが保証されます。

同様に、メソッドの戻り値の型の制限がデリゲートの戻り値の型より多いと、メソッドの戻り値がデリゲートの戻り値の型に安全にキャストされることが保証されるため、デリゲートの戻り値の型とメソッドの戻り値の型には互換性があります。

たとえば、 型のパラメーターと 戻り値の型HashtableObjectを持つデリゲートは、 型のパラメーターと 型ObjectHashtable戻り値を持つメソッドを表すことができます。

こちらもご覧ください

適用対象

CreateDelegate(Type, Object, String)

指定したクラス インスタンスに対して呼び出す指定したインスタンス メソッドを表す、指定した型のデリゲートを作成します。

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
Public Shared Function CreateDelegate (type As Type, target As Object, method As String) As Delegate

パラメーター

type
Type

作成するデリゲートの Type

target
Object

method を呼び出す対象のクラス インスタンス。

method
String

デリゲートによって表されるインスタンス メソッドの名前。

戻り値

指定したクラス インスタンスに対して呼び出す指定したインスタンス メソッドを表す、指定した型のデリゲート。

例外

typenullです。

または

targetnullです。

または

methodnullです。

typeMulticastDelegate を継承しません。

- または -

typeRuntimeType ではありません。 「リフレクションのランタイム型」を参照してください。

- または -

method はインスタンス メソッドではありません。

- または -

method をバインドできません (たとえば、これが見つからないなど)。

typeInvoke メソッドが見つかりません。

method へのアクセスに必要なアクセス許可が呼び出し元にありません。

注釈

このメソッドは、インスタンス メソッドのデリゲートのみを作成します。 インスタンス メソッドは、 クラスのインスタンスに関連付けられているメソッドです。静的メソッドは、クラス自体に関連付けられているメソッドです。

このメソッド オーバーロードは、 メソッド オーバーロードを呼び出すのCreateDelegate(Type, Object, String, Boolean, Boolean)と同じで、 に と truethrowOnBindFailurefalseignoreCase指定します。

Note

.NET Framework 2.0 Service Pack 1 以降では、このメソッドを使用して、フラグを使用して呼び出し元が許可ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccessされている場合、および非パブリック メソッドの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合は、非パブリック メソッドにアクセスできます。 ( リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。

この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

こちらもご覧ください

適用対象

CreateDelegate(Type, Object, MethodInfo)

指定された静的メソッドまたはインスタンス メソッドを表す、指定した型のデリゲートを、第 1 引数を指定して作成します。

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);
public static Delegate CreateDelegate (Type type, object firstArgument, System.Reflection.MethodInfo method);
static member CreateDelegate : Type * obj * System.Reflection.MethodInfo -> Delegate
Public Shared Function CreateDelegate (type As Type, firstArgument As Object, method As MethodInfo) As Delegate

パラメーター

type
Type

作成するデリゲートの Type

firstArgument
Object

デリゲートのバインド先のオブジェクト。methodstatic (Visual Basic の場合は Shared) として扱う場合は null

method
MethodInfo

デリゲートが表す静的メソッドまたはインスタンス メソッドの情報を記述する MethodInfo

戻り値

指定した静的メソッドまたはインスタンス メソッドを表すための、指定した型のデリゲート。

例外

typenullです。

または

methodnullです。

typeMulticastDelegate を継承しません。

- または -

typeRuntimeType ではありません。 「リフレクションのランタイム型」を参照してください。

- または -

method はバインドできません。

- または -

methodRuntimeMethodInfo ではありません。 「リフレクションのランタイム型」を参照してください。

typeInvoke メソッドが見つかりません。

method へのアクセスに必要なアクセス許可が呼び出し元にありません。

このセクションには、3 つのコード例が含まれています。 最初の例では、作成できるデリゲートの 4 種類を示します。インスタンス メソッドで閉じる、インスタンス メソッドで開く、静的メソッドで開く、静的メソッドで閉じるなどです。

2 番目のコード例では、互換性のあるパラメーター型と戻り値の型を示します。

3 番目のコード例では、1 つのデリゲート型を定義し、デリゲート型が表すことができるすべてのメソッドを示します。

例 1

次のコード例では、 メソッドのこのオーバーロードを使用してデリゲートを作成する 4 つの方法を CreateDelegate 示します。

Note

MethodInfoCreateDelegate指定firstArgumentする メソッドには 2 つのオーバーロードがあります。その機能は同じですが、1 つはバインドに失敗した場合にスローするかどうかを指定でき、もう 1 つは常に スローします。 このコード例では、両方のオーバーロードを使用します。

この例では、静的メソッドとインスタンス メソッド を使用して クラスCを宣言し、次の C 3 つのデリゲート型D1を宣言します。 のインスタンスと文字列を受け取り、D2文字列を受け取り、D3引数がありません。M2M1

という名前 Example の 2 番目のクラスには、デリゲートを作成するコードが含まれています。

  • のインスタンスで閉じられている 型 D2Cデリゲートが、インスタンス メソッド M1に対して作成されます。 バインドされた インスタンス C が常に使用されることを示すために、異なる文字列で呼び出されます。

  • インスタンス メソッド M1に対して、開いているインスタンス メソッドを表す 型D1のデリゲートが作成されます。 デリゲートの呼び出し時にインスタンスを渡す必要があります。

  • 静的メソッド M2に対して、開いている静的メソッドを表す 型D2のデリゲートが作成されます。

  • 最後に、静的メソッド M2に対して、文字列で閉じられている 型D3のデリゲートが作成されます。 メソッドは、バインドされた文字列を使用することを示すために呼び出されます。

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!
 */
open System
open System.Reflection

// A sample class with an instance method and a static method.
type C(id) =
    member _.M1(s) =
        printfn $"Instance method M1 on C:  id = %i{id}, s = %s{s}"

    static member M2(s) =
        printfn $"Static method M2 on C:  s = %s{s}"
    
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit

let c1 = C 42

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

printfn "\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.
let 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 then
    let d2 = test :?> D2

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

printfn "\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.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1

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

printfn "\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.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2

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

printfn "\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.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3

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

// 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!
'

例 2

次のコード例は、パラメーター型と戻り値の型の互換性を示しています。

Note

このコード例では、 メソッドのオーバーロードを CreateDelegate(Type, MethodInfo) 使用します。 受け取る MethodInfo 他のオーバーロードの使用も同様です。

このコード例では、 という名前Baseの基底クラスと からBase派生する という名前Derivedのクラスを定義しています。 派生クラスには、 型のパラメーターを static 1 つ、戻り値の型Baseを持つ という名前MyMethodの (Shared Visual Basic の場合) メソッドがありますDerived。 このコード例では、 型のパラメーターが 1 つ、戻り値の型Derivedが の という名前ExampleBaseデリゲートも定義しています。

このコード例では、 という名前 Example のデリゲートを使用して メソッド MyMethodを表すことができることを示します。 メソッドは、次の理由でデリゲートにバインドできます。

  • デリゲート () のパラメーター型は、Derived() のパラメーター型よりも制限が厳しいため、デリゲートのMyMethodBase引数を に渡しても常にMyMethod安全です。

  • (Derived) の戻り値のMyMethod型は、デリゲート (Base) のパラメーター型よりも制限が厳しいため、メソッドの戻り値の型をデリゲートの戻り値の型にキャストしても常に安全です。

このコード例では、出力は生成されません。

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());
    }
}
open System
open System.Reflection

// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end

type Derived() =
    inherit 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.
    static member MyMethod(arg: Base) =
        Derived()

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base

// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static

// Get a MethodInfo that represents MyMethod.
let 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).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example

// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
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

例 3

次のコード例は、 メソッドを使用してデリゲートを作成し、1 つのデリゲート型が CreateDelegate 表すことができるすべてのメソッドを示しています。

Note

MethodInfoCreateDelegate指定firstArgumentする メソッドには 2 つのオーバーロードがあります。その機能は同じですが、1 つはバインドに失敗した場合にスローするかどうかを指定でき、もう 1 つは常に スローします。 このコード例では、両方のオーバーロードを使用します。

このコード例では、 と の 2 つのクラスとFCDの 1 つの引数を持つデリゲート型を定義していますC。 クラスには、一致する静的メソッドとインスタンス メソッド M1M3、および M4クラス C があり、引数を持たないインスタンス メソッド M2 もあります。

という名前 Example の 3 番目のクラスには、デリゲートを作成するコードが含まれています。

  • デリゲートは、型と型CFのインスタンス メソッドM1に対して作成されます。各デリゲートは、それぞれの型のインスタンスで閉じられます。 型Cの メソッドM1は、IDバインドされたインスタンスのプロパティと 引数のプロパティを表示します。

  • Cの メソッドM2に対してデリゲートが作成されます。 これは、デリゲートの引数がインスタンス メソッドの非表示の最初の引数を表す、開いているインスタンス デリゲートです。 メソッドには他の引数はありません。 静的メソッドであるかのように呼び出されます。

  • デリゲートは、型と型CFの静的メソッドM3に対して作成されます。これらは、開いている静的デリゲートです。

  • 最後に、型と型CFの静的メソッドM4に対してデリゲートが作成されます。各メソッドは、宣言する型を最初の引数として持ち、型のインスタンスが指定されるため、デリゲートは最初の引数で閉じられます。 型Cの メソッドM4は、IDバインドされたインスタンスのプロパティと 引数のプロパティを表示します。

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
*/
open System

// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
type C(id) =
    member _.ID = id 

    member _.M1(c: C) =
        printfn $"Instance method M1(C c) on C:  this.id = {id}, c.ID = {c.ID}"

    member _.M2() =
        printfn $"Instance method M2() on C:  this.id = {id}"

    static member M3(c: C) =
        printfn $"Static method M3(C c) on C:  c.ID = {c.ID}"

    static member M4(c1: C, c2: C) =
        printfn $"Static method M4(C c1, C c2) on C:  c1.ID = {c1.ID}, c2.ID = {c2.ID}"

// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
type D = delegate of C -> unit


type F() =
    member _.M1(c: C) =
        printfn $"Instance method M1(C c) on F:  c.ID = {c.ID}"

    member _.M3(c: C) =
        printfn $"Static method M3(C c) on F:  c.ID = {c.ID}"

    member _.M4(f: F, c: C) =
        printfn $"Static method M4(F f, C c) on F:  c.ID = {c.ID}"

[<EntryPoint>]
let main _ =
    let c1 = C 42
    let c2 = C 1491
    let f1 = F()

    // Instance method with one argument of type C.
    let cmi1 = typeof<C>.GetMethod "M1"
    // Instance method with no arguments.
    let cmi2 = typeof<C>.GetMethod "M2"
    // Static method with one argument of type C.
    let cmi3 = typeof<C>.GetMethod "M3"
    // Static method with two arguments of type C.
    let cmi4 = typeof<C>.GetMethod "M4"

    // Instance method with one argument of type C.
    let fmi1 = typeof<F>.GetMethod "M1"
    // Static method with one argument of type C.
    let fmi3 = typeof<F>.GetMethod "M3"
    // Static method with an argument of type F and an argument
    // of type C.
    let fmi4 = typeof<F>.GetMethod "M4"

    printfn "\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.
    let d = Delegate.CreateDelegate(typeof<D>, c1, cmi1) :?> D
    d.Invoke c2
    let d =  Delegate.CreateDelegate(typeof<D>, f1, fmi1) :?> D
    d.Invoke 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.
    let d = Delegate.CreateDelegate(typeof<D>, null, cmi2) :?> D
    d.Invoke c1

    printfn "\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.
    let d = Delegate.CreateDelegate(typeof<D>, null, cmi3) :?> D
    d.Invoke c1
    let d = Delegate.CreateDelegate(typeof<D>, null, fmi3) :?> D
    d.Invoke c1

    printfn "\nA static method on any type, with an argument of"
    printfn "    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.
    let d = Delegate.CreateDelegate(typeof<D>, c1, cmi4) :?> D
    d.Invoke c2
    let 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).
    match test with
    | :? D as d ->
        d.Invoke c2
    | _ -> ()
    0

// 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指定することとtrue同じです。 これら 2 つのオーバーロードは、デリゲートを作成する最も柔軟な方法を提供します。 これらを使用して、静的メソッドまたはインスタンス メソッドのデリゲートを作成し、必要に応じて最初の引数を指定できます。

Note

最初の引数を指定しない場合は、 メソッドのオーバーロードを使用して CreateDelegate(Type, MethodInfo) パフォーマンスを向上させます。

デリゲート型と メソッドには、互換性のある戻り値の型が必要です。 つまり、 の戻り値の型は、 の method 戻り値の型 typeに割り当て可能である必要があります。

が指定された場合firstArgument、デリゲートが呼び出firstArgumentされるたびに にmethod渡されます。デリゲートにバインドされると言われ、デリゲートは最初の引数で閉じられていると言われます。 が static ( Visual Basic の場合) の場合method、デリゲートの呼び出し時に指定された引数リストには、最初の を除くすべてのパラメーターが含まれます。がインスタンス メソッドの場合methodは、firstArgument非表示のインスタンス パラメーター (C# では または Visual Basic で によってMe表されますthis) に渡Sharedされます。

が指定されている場合 firstArgument 、 の最初の method パラメーターは参照型である必要があり、その型と firstArgument 互換性がある必要があります。

重要

static (Shared Visual Basic の場合) で、最初のパラメーターが 型Objectまたは ValueTypeの場合methodは、firstArgument値型にすることができます。 この場合 firstArgument 、自動的にボックス化されます。 C# または Visual Basic 関数呼び出しの場合と同様に、他の引数に対して自動ボックス化は行われません。

が null 参照でmethod、インスタンス メソッドの場合firstArgument、結果はデリゲート型typeの シグネチャと の methodシグネチャによって異なります。

  • のシグネチャ type に の非表示の最初の methodパラメーターが明示的に含まれている場合、デリゲートは開いているインスタンス メソッドを表すと言われます。 デリゲートが呼び出されると、引数リストの最初の引数が の非表示インスタンス パラメーター methodに渡されます。

  • type のシグネチャが一致するmethod場合 (つまり、すべてのパラメーター型に互換性があります)、デリゲートは null 参照で閉じられると言われます。 デリゲートの呼び出しは、null インスタンスでインスタンス メソッドを呼び出すことと似ていますが、これは特に便利な操作ではありません。

が null 参照であり、 method が静的である場合firstArgument、結果はデリゲート型typemethodのシグネチャによって異なります。

  • type のシグネチャmethodが一致する場合 (つまり、すべてのパラメーター型に互換性があります)、デリゲートはオープン静的メソッドを表すと言います。 これは、静的メソッドの最も一般的なケースです。 この場合、 メソッドのオーバーロードを使用すると、パフォーマンスが CreateDelegate(Type, MethodInfo) 若干向上します。

  • のシグネチャ type が の 2 番目の method パラメーターで始まり、残りのパラメーター型に互換性がある場合、デリゲートは null 参照で閉じられると言われます。 デリゲートが呼び出されると、 の最初のパラメーター methodに null 参照が渡されます。

Note

.NET Framework 2.0 Service Pack 1 以降では、このメソッドを使用して、呼び出し元が フラグを使用ReflectionPermissionFlag.RestrictedMemberAccessして許可ReflectionPermissionされている場合、および非パブリック メソッドの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合は、非パブリック メソッドにアクセスできます。 ( リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。

この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

互換性のあるパラメーター型と戻り値の型

デリゲートのパラメーター型と戻り値の型は、デリゲートが表すメソッドのパラメーター型および戻り値の型と互換性がある必要があります。型は正確に一致する必要はありません。

デリゲートのパラメーターにメソッドのパラメーターよりも限定的な型が指定された場合、両者のパラメーター間に型の互換性があると見なされます。これによって、デリゲートに渡された引数が、メソッドに対して安全に渡されることが保証されます。

同様に、メソッドの戻り値の型の制限がデリゲートの戻り値の型より多いと、メソッドの戻り値がデリゲートの戻り値の型に安全にキャストされることが保証されるため、デリゲートの戻り値の型とメソッドの戻り値の型には互換性があります。

たとえば、 型のパラメーターと戻り値の型を持つデリゲートは、 型 HashtableObject パラメーターと型 Object の戻り値 Hashtableを持つメソッドを表すことができます。

デリゲートが表すことができるメソッドの決定

のこのオーバーロードによって提供される柔軟性を考えるもう 1 つの便利な方法は、任意の CreateDelegate デリゲートがメソッド シグネチャとメソッドの種類 (静的とインスタンス) の 4 つの異なる組み合わせを表すことができるということです。 型の 1 つの引数を持つデリゲート DCを考えてみましょう。 次に、すべてのケースで一致する D 必要があるため、戻り値の型を無視して、 を表すことができるメソッドについて説明します。

  • D は、インスタンス メソッドが属する型に関係なく、 型 Cの引数が 1 つだけの任意のインスタンス メソッドを表すことができます。 が呼び出されると CreateDelegatefirstArgument は 型 method のインスタンスに属し、結果のデリゲートはそのインスタンスで閉じられていると言われます。 (単純に、 D が null 参照の場合 firstArgument は、null 参照で閉じることもできます)。

  • D は、引数を持たない の C インスタンス メソッドを表すことができます。 が呼び出されると CreateDelegatefirstArgument は null 参照です。 結果のデリゲートは開いているインスタンス メソッドを表し、 の C インスタンスは呼び出されるたびに指定する必要があります。

  • D は、 型 Cの 1 つの引数を受け取る静的メソッドを表し、そのメソッドは任意の型に属することができます。 が呼び出されると CreateDelegatefirstArgument は null 参照です。 結果のデリゲートは開いている静的メソッドを表し、 の C インスタンスは呼び出されるたびに指定する必要があります。

  • D型に属し、型とCFF 2 つの引数を持つ静的メソッドを表すことができます。 が呼び出されると CreateDelegatefirstArgument は の Fインスタンスです。 結果のデリゲートは、 のそのインスタンス Fで閉じられる静的メソッドを表します。 と CF同じ型の場合、静的メソッドにはその型の 2 つの引数があることに注意してください。 (この場合、 D が null 参照の場合 firstArgument 、 は null 参照で閉じられます)。

こちらもご覧ください

適用対象

CreateDelegate(Type, Type, String)

指定したクラスの指定した静的メソッドを表す、指定した型のデリゲートを作成します。

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
Public Shared Function CreateDelegate (type As Type, target As Type, method As String) As Delegate

パラメーター

type
Type

作成するデリゲートの Type

target
Type

method を実装するクラスを表す Type

method
String

デリゲートによって表される静的メソッドの名前。

戻り値

指定したクラスの指定した静的メソッドを表す、指定した型のデリゲート。

例外

typenullです。

または

targetnullです。

または

methodnullです。

typeMulticastDelegate を継承しません。

- または -

typeRuntimeType ではありません。 「リフレクションのランタイム型」を参照してください。

- または -

targetRuntimeType ではありません。

- または -

target はオープン ジェネリック型です。 つまり、その ContainsGenericParameters プロパティは true です。

- または -

methodstatic メソッド (Visual Basic では Shared メソッド) ではありません。

- または -

見つからないなどの原因により、method をバインドできません。また、throwOnBindFailuretrue です。

typeInvoke メソッドが見つかりません。

method へのアクセスに必要なアクセス許可が呼び出し元にありません。

注釈

このメソッドは、静的メソッド専用のデリゲートを作成します。 インスタンス メソッドは、 クラスのインスタンスに関連付けられているメソッドです。静的メソッドは、 クラス自体に関連付けられているメソッドです。

このメソッド オーバーロードは、 に と を指定してCreateDelegate(Type, Type, String, Boolean, Boolean)、メソッド オーバーロードを呼び出すことfalseignoreCasetruethrowOnBindFailure同じです。

Note

.NET Framework 2.0 Service Pack 1 以降では、このメソッドを使用して、呼び出し元が フラグを使用ReflectionPermissionFlag.RestrictedMemberAccessして許可ReflectionPermissionされている場合、および非パブリック メソッドの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合は、非パブリック メソッドにアクセスできます。 ( リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。

この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

こちらもご覧ください

適用対象

CreateDelegate(Type, MethodInfo)

指定したメソッドを表す、指定した型のデリゲートを作成します。

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
Public Shared Function CreateDelegate (type As Type, method As MethodInfo) As Delegate

パラメーター

type
Type

作成するデリゲートの Type

method
MethodInfo

デリゲートが表す静的メソッドまたはインスタンス メソッドの情報を記述する MethodInfo

戻り値

指定したメソッドを表す、指定した型のデリゲート。

例外

typenullです。

または

methodnullです。

typeMulticastDelegate を継承しません。

- または -

typeRuntimeType ではありません。 「リフレクションのランタイム型」を参照してください。

- または -

method はバインドできません。

- または -

methodRuntimeMethodInfo ではありません。 「リフレクションのランタイム型」を参照してください。

typeInvoke メソッドが見つかりません。

method へのアクセスに必要なアクセス許可が呼び出し元にありません。

このセクションには、2 つのコード例が含まれています。 最初の例では、このメソッド オーバーロードを使用して作成できる 2 種類のデリゲートを示します。インスタンス メソッドを介して開き、静的メソッドで開きます。

2 番目のコード例では、互換性のあるパラメーター型と戻り値の型を示します。

例 1

次のコード例は、 メソッドのこのオーバーロードを使用してデリゲートを作成する 2 つの方法を CreateDelegate 示しています。

Note

メソッドには、最初の CreateDelegate 引数ではなく を MethodInfo 指定する 2 つのオーバーロードがあります。その機能は同じですが、1 つはバインドに失敗した場合に スローするかどうかを指定でき、もう 1 つは常に をスローすることを除きます。 このコード例では、両方のオーバーロードを使用します。

この例では、静的メソッドとインスタンス メソッド M2 を使用して クラスCを宣言し、 のインスタンスCM1と文字列を受け取り、D2文字列を受け取る 2 つのデリゲート型D1を宣言します。

という名前 Example の 2 番目のクラスには、デリゲートを作成するコードが含まれています。

  • 開いているインスタンス メソッドを表す 型 D1のデリゲートが、インスタンス メソッド M1に対して作成されます。 デリゲートが呼び出されるときに、インスタンスを渡す必要があります。

  • 静的メソッド M2に対して、開いている静的メソッドを表す 型D2のデリゲートが作成されます。

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!
 */
open System
open System.Reflection

// A sample class with an instance method and a static method.
type C(id) =
    member _.M1(s) =
        printfn $"Instance method M1 on C:  id = %i{id}, s = %s{s}"

    static member M2(s) =
        printfn $"Static method M2 on C:  s = %s{s}"
    
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit

let c1 = C 42

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

printfn "\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.
let 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 then
    let d2 = test :?> D2

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

printfn "\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.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1

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

printfn "\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.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2

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

printfn "\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.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3

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

// 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!
'

例 2

次のコード例は、パラメーター型と戻り値の型の互換性を示しています。

このコード例では、 という名前Baseの基底クラスと、 からBase派生する という名前Derivedのクラスを定義します。 派生クラスには、 型の static 1 つのパラメーターと戻り値の型Baseを持つ という名前MyMethodの (Shared Visual Basic の場合) メソッドがありますDerived。 また、このコード例では、 型のパラメーターと戻り値の型Derivedを持つ という名前ExampleBaseデリゲートも定義しています。

このコード例では、 という名前 Example のデリゲートを使用して メソッド MyMethodを表すことができることを示します。 メソッドは、次の理由でデリゲートにバインドできます。

  • デリゲート () のパラメーター型は、Derived() のパラメーター型よりも制限が厳しく、デリゲートのMyMethodBase引数を に渡しても常にMyMethod安全です。

  • (Derived) の戻り値のMyMethod型は、デリゲート (Base) のパラメーター型よりも制限が厳しいため、メソッドの戻り値の型をデリゲートの戻り値の型にキャストしても常に安全です。

このコード例では、出力は生成されません。

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());
    }
}
open System
open System.Reflection

// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end

type Derived() =
    inherit 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.
    static member MyMethod(arg: Base) =
        Derived()

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base

// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static

// Get a MethodInfo that represents MyMethod.
let 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).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example

// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
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 では、このメソッド オーバーロードによって静的メソッドのみのデリゲートが作成されます。 .NET Framework バージョン 2.0 では、このメソッド オーバーロードは、開いているインスタンス メソッド デリゲートを作成することもできます。つまり、インスタンス メソッドの非表示の最初の引数を明示的に指定するデリゲートです。 詳細な説明については、より一般的な CreateDelegate(Type, Object, MethodInfo) メソッド オーバーロードを参照してください。これにより、インスタンスまたは静的メソッドに対して開いているデリゲートまたは閉じたデリゲートのすべての組み合わせを作成でき、必要に応じて最初の引数を指定できます。

Note

このメソッド のオーバーロードは、デリゲートが最初の引数で閉じられない場合に使用する必要があります。その場合はやや高速であるためです。

このメソッド オーバーロードは、 メソッド オーバーロードを呼び出し、 に CreateDelegate(Type, MethodInfo, Boolean)throwOnBindFailure指定することとtrue同じです。

Note

.NET Framework 2.0 Service Pack 1 以降では、このメソッドを使用して、呼び出し元が フラグを使用ReflectionPermissionFlag.RestrictedMemberAccessして許可ReflectionPermissionされている場合、および非パブリック メソッドの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合は、非パブリック メソッドにアクセスできます。 ( リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。

この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

互換性のあるパラメーター型と戻り値の型

.NET Framework バージョン 2.0 では、このメソッド オーバーロードを使用して作成されたデリゲートのパラメーター型と戻り値の型は、デリゲートが表すメソッドのパラメーター型と戻り値の型と互換性がある必要があります。型が正確に一致する必要はありません。 これは、.NET Framework バージョン 1.0 および 1.1 でのバインディング動作の緩和を表します。この場合、型は正確に一致する必要があります。

デリゲートのパラメーターにメソッドのパラメーターよりも限定的な型が指定された場合、両者のパラメーター間に型の互換性があると見なされます。これによって、デリゲートに渡された引数が、メソッドに対して安全に渡されることが保証されます。

同様に、メソッドの戻り値の型の制限がデリゲートの戻り値の型より多いと、メソッドの戻り値がデリゲートの戻り値の型に安全にキャストされることが保証されるため、デリゲートの戻り値の型とメソッドの戻り値の型には互換性があります。

たとえば、 型のパラメーターと戻り値の型を持つデリゲートは、 型 HashtableObject パラメーターと型 Object の戻り値 Hashtableを持つメソッドを表すことができます。

こちらもご覧ください

適用対象