DynamicMethod コンストラクター

定義

動的メソッドを作成します。

オーバーロード

名前 説明
DynamicMethod(String, Type, Type[])

メソッド名、戻り値の型、およびパラメーター型を指定して、匿名でホストされる動的メソッドを初期化します。

DynamicMethod(String, Type, Type[], Boolean)

匿名でホストされる動的メソッドを初期化し、メソッド名、戻り値の型、パラメーターの型、および動的メソッドのMicrosoft中間言語 (MSIL) によってアクセスされる型とメンバーの Just-In-Time (JIT) 可視性チェックをスキップするかどうかを指定します。

DynamicMethod(String, Type, Type[], Module)

メソッド名、戻り値の型、パラメーター型、およびモジュールを指定して、モジュールに対してグローバルな動的メソッドを作成します。

DynamicMethod(String, Type, Type[], Type)

動的メソッドを作成し、メソッド名、戻り値の型、パラメーター型、および動的メソッドが論理的に関連付けられている型を指定します。

DynamicMethod(String, Type, Type[], Module, Boolean)

メソッド名、戻り値の型、パラメーター型、モジュール、および動的メソッドのMicrosoft中間言語 (MSIL) によってアクセスされる型とメンバーに対して Just-In-Time (JIT) 可視性チェックをスキップするかどうかを指定して、モジュールにグローバルな動的メソッドを作成します。

DynamicMethod(String, Type, Type[], Type, Boolean)

動的メソッドを作成し、メソッド名、戻り値の型、パラメーター型、動的メソッドが論理的に関連付けられている型、および動的メソッドのMicrosoft中間言語 (MSIL) によってアクセスされる型とメンバーに対して Just-In-Time (JIT) 可視性チェックをスキップするかどうかを指定します。

DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Module, Boolean)

メソッド名、属性、呼び出し規則、戻り値の型、パラメーター型、モジュール、および動的メソッドのMicrosoft中間言語 (MSIL) によってアクセスされる型とメンバーに対して Just-In-Time (JIT) 可視性チェックをスキップするかどうかを指定して、モジュールにグローバルな動的メソッドを作成します。

DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type, Boolean)

動的メソッドを作成し、メソッド名、属性、呼び出し規則、戻り値の型、パラメーター型、動的メソッドが論理的に関連付けられている型、および動的メソッドのMicrosoft中間言語 (MSIL) によってアクセスされる型とメンバーに対して Just-In-Time (JIT) 可視性チェックをスキップするかどうかを指定します。

DynamicMethod(String, Type, Type[])

メソッド名、戻り値の型、およびパラメーター型を指定して、匿名でホストされる動的メソッドを初期化します。

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type())

パラメーター

name
String

動的メソッドの名前。 長さ 0 の文字列を指定できますが、 nullすることはできません。

returnType
Type

動的メソッドの戻り値の型を指定する Type オブジェクト。メソッドに戻り値の型がない場合は null

parameterTypes
Type[]

動的メソッドのパラメーターの型を指定する Type オブジェクトの配列。メソッドにパラメーターがない場合は null

例外

parameterTypesの要素がnullまたはVoidです。

namenullです。

.NET Framework と .NET Core バージョンが 2.1 より前の場合: returnType は、IsByReftrue を返す型です。

注釈

このコンストラクターによって作成される動的メソッドは、既存の型またはモジュールではなく匿名アセンブリに関連付けられます。 匿名アセンブリは、動的メソッドのサンドボックス環境を提供すること、つまり他のコードから分離するためにのみ存在します。 この環境により、部分的に信頼されたコードによって動的メソッドが安全に出力および実行されます。

このコンストラクターは、動的メソッドのMicrosoft中間言語 (MSIL) に対して Just-In-Time (JIT) 可視性チェックを適用することを指定します。 つまり、動的メソッドのコードは、パブリック クラスのパブリック メソッドにアクセスできます。 メソッドが privateprotected、または internal (Visual Basic の Friend) の型またはメンバーにアクセスしようとすると、例外がスローされます。 JIT 可視性チェックをスキップする機能が制限されている動的メソッドを作成するには、 DynamicMethod(String, Type, Type[], Boolean) コンストラクターを使用します。

匿名でホストされる動的メソッドが構築されると、出力アセンブリの呼び出し履歴が含まれます。 メソッドが呼び出されると、実際の呼び出し元のアクセス許可ではなく、出力アセンブリのアクセス許可が使用されます。 したがって、動的メソッドは、信頼レベルが高いアセンブリに渡されて実行された場合でも、動的メソッドを生成したアセンブリの特権よりも高いレベルで実行することはできません。

このコンストラクターは、メソッド属性 MethodAttributes.PublicMethodAttributes.Staticを指定し、呼び出し規則 CallingConventions.Standard

Note

このコンストラクターは、.NET Framework 3.5 以降で導入されました。

こちらもご覧ください

適用対象

DynamicMethod(String, Type, Type[], Boolean)

匿名でホストされる動的メソッドを初期化し、メソッド名、戻り値の型、パラメーターの型、および動的メソッドのMicrosoft中間言語 (MSIL) によってアクセスされる型とメンバーの Just-In-Time (JIT) 可視性チェックをスキップするかどうかを指定します。

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, bool restrictedSkipVisibility);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), restrictedSkipVisibility As Boolean)

パラメーター

name
String

動的メソッドの名前。 長さ 0 の文字列を指定できますが、 nullすることはできません。

returnType
Type

動的メソッドの戻り値の型を指定する Type オブジェクト。メソッドに戻り値の型がない場合は null

parameterTypes
Type[]

動的メソッドのパラメーターの型を指定する Type オブジェクトの配列。メソッドにパラメーターがない場合は null

restrictedSkipVisibility
Boolean

true 動的メソッドの MSIL によってアクセスされる型とメンバーに対する JIT 可視性チェックをスキップするには、次の制限があります。これらの型とメンバーを含むアセンブリの信頼レベルは、動的メソッドを出力する呼び出し履歴の信頼レベル以下である必要があります。それ以外の場合は false

例外

parameterTypesの要素がnullまたはVoidです。

namenullです。

.NET Framework と .NET Core バージョンが 2.1 より前の場合: returnType は、IsByReftrue を返す型です。

注釈

このコンストラクターによって作成される動的メソッドは、既存の型またはモジュールではなく匿名アセンブリに関連付けられます。 匿名アセンブリは、動的メソッドのサンドボックス環境を提供すること、つまり他のコードから分離するためにのみ存在します。 この環境により、部分的に信頼されたコードによって動的メソッドが安全に出力および実行されます。

匿名でホストされる動的メソッドは、privateprotected、または internal (Visual Basic の Friend) である型またはメンバーに自動アクセスすることはできません。 これは、既存の型またはモジュールに関連付けられている動的メソッドとは異なり、関連付けられているスコープ内の非表示のメンバーにアクセスできます。

truerestrictedSkipVisibilityに指定してください。これは、動的メソッドがprivateprotected、またはinternalする型やメンバーにアクセスする必要がある場合に備えています。 これにより、動的メソッドにこれらのメンバーへのアクセスが制限されます。 つまり、次の条件が満たされている場合にのみ、メンバーにアクセスできます。

  • ターゲット メンバーは、動的メソッドを出力する呼び出し履歴以下の信頼レベルを持つアセンブリに属します。

  • 動的メソッドを出力する呼び出し履歴には、ReflectionPermission フラグを持つReflectionPermissionFlag.RestrictedMemberAccessが付与されます。 これは、コードが完全信頼で実行される場合に常に当てはまります。 部分的に信頼されたコードの場合、ホストが明示的にアクセス許可を付与する場合にのみ true になります。

    Important

    アクセス許可が付与されていない場合は、このコンストラクターが呼び出されたときではなく、 CreateDelegate が呼び出されたとき、または動的メソッドが呼び出されたときにセキュリティ例外がスローされます。 動的メソッドを出力するために特別なアクセス許可は必要ありません。

たとえば、 restrictedSkipVisibilitytrue に設定して作成された動的メソッドは、呼び出し履歴に制限付きメンバー アクセスが許可されている場合、呼び出し履歴上の任意のアセンブリのプライベート メンバーにアクセスできます。 呼び出し履歴で部分的に信頼されたコードを使用して動的メソッドが作成された場合、そのようなアセンブリは完全に信頼されているため、.NET Framework アセンブリ内の型のプライベート メンバーにアクセスできません。

restrictedSkipVisibilityfalseされている場合、JIT 可視性チェックが適用されます。 動的メソッドのコードはパブリッククラスのパブリックメソッドにアクセスできます。例外は、privateprotected、またはinternalな型やメンバーにアクセスしようとするとスローされます。

匿名でホストされる動的メソッドが構築されると、出力アセンブリの呼び出し履歴が含まれます。 メソッドが呼び出されると、実際の呼び出し元のアクセス許可ではなく、出力呼び出し履歴のアクセス許可が使用されます。 したがって、動的メソッドは、信頼レベルが高いアセンブリに渡されて実行された場合でも、動的メソッドを生成したアセンブリの特権よりも高いレベルで実行することはできません。

このコンストラクターは、メソッド属性 MethodAttributes.PublicMethodAttributes.Staticを指定し、呼び出し規則 CallingConventions.Standard

Note

このコンストラクターは、.NET Framework 3.5 以降で導入されました。

こちらもご覧ください

適用対象

DynamicMethod(String, Type, Type[], Module)

メソッド名、戻り値の型、パラメーター型、およびモジュールを指定して、モジュールに対してグローバルな動的メソッドを作成します。

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, System.Reflection.Module m);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * System.Reflection.Module -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), m As Module)

パラメーター

name
String

動的メソッドの名前。 長さ 0 の文字列を指定できますが、 nullすることはできません。

returnType
Type

動的メソッドの戻り値の型を指定する Type オブジェクト。メソッドに戻り値の型がない場合は null

parameterTypes
Type[]

動的メソッドのパラメーターの型を指定する Type オブジェクトの配列。メソッドにパラメーターがない場合は null

m
Module

動的メソッドを論理的に関連付けるモジュールを表す Module

例外

parameterTypesの要素がnullまたはVoidです。

-または-

m は、動的メソッドの匿名ホスティングを提供するモジュールです。

namenullです。

-または-

mnullです。

.NET Framework と .NET Core バージョンが 2.1 より前の場合: returnType は、IsByReftrue を返す型です。

次のコード例では、2 つのパラメーターを受け取る動的メソッドを作成します。 この例では、最初のパラメーターをコンソールに出力する単純な関数本体を出力し、2 番目のパラメーターをメソッドの戻り値として使用します。 この例では、デリゲートを作成してメソッドを完成させ、さまざまなパラメーターでデリゲートを呼び出し、最後に Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) メソッドを使用して動的メソッドを呼び出します。

using System;
using System.Reflection;
using System.Reflection.Emit;
using Microsoft.VisualBasic;

public class Test
{
    // Declare a delegate that will be used to execute the completed
    // dynamic method.
    private delegate int HelloInvoker(string msg, int ret);

    public static void Main()
    {
        // Create an array that specifies the types of the parameters
        // of the dynamic method. This method has a string parameter
        // and an int parameter.
        Type[] helloArgs = {typeof(string), typeof(int)};

        // Create a dynamic method with the name "Hello", a return type
        // of int, and two parameters whose types are specified by the
        // array helloArgs. Create the method in the module that
        // defines the Test class.
        DynamicMethod hello = new DynamicMethod("Hello",
            typeof(int),
            helloArgs,
            typeof(Test).Module);

        // Create an array that specifies the parameter types of the
        // overload of Console.WriteLine to be used in Hello.
        Type[] writeStringArgs = {typeof(string)};
        // Get the overload of Console.WriteLine that has one
        // String parameter.
        MethodInfo writeString =
            typeof(Console).GetMethod("WriteLine", writeStringArgs);

        // Get an ILGenerator and emit a body for the dynamic method.
        ILGenerator il = hello.GetILGenerator();
        // Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0);
        // Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, null);
        // The Hello method returns the value of the second argument;
        // to do this, load the onto the stack and return.
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ret);

        // Create a delegate that represents the dynamic method. This
        // action completes the method, and any further attempts to
        // change the method will cause an exception.
        HelloInvoker hi =
            (HelloInvoker) hello.CreateDelegate(typeof(HelloInvoker));

        // Use the delegate to execute the dynamic method. Save and
        // print the return value.
        int retval = hi("\r\nHello, World!", 42);
        Console.WriteLine("Executing delegate hi(\"Hello, World!\", 42) returned {0}",
            retval);

        // Do it again, with different arguments.
        retval = hi("\r\nHi, Mom!", 5280);
        Console.WriteLine("Executing delegate hi(\"Hi, Mom!\", 5280) returned {0}",
            retval);

        // Create an array of arguments to use with the Invoke method.
        object[] invokeArgs = {"\r\nHello, World!", 42};
        // Invoke the dynamic method using the arguments. This is much
        // slower than using the delegate, because you must create an
        // array to contain the arguments, and ValueType arguments
        // must be boxed.
        object objRet = hello.Invoke(null, invokeArgs);
        Console.WriteLine("hello.Invoke returned {0}", objRet);
    }
}
Imports System.Reflection
Imports System.Reflection.Emit

Public Class Test
    ' Declare a delegate that will be used to execute the completed
    ' dynamic method. 
    Private Delegate Function HelloInvoker(ByVal msg As String, _
        ByVal ret As Integer) As Integer

    Public Shared Sub Main()
        ' Create an array that specifies the types of the parameters
        ' of the dynamic method. This method has a String parameter
        ' and an Integer parameter.
        Dim helloArgs() As Type = {GetType(String), GetType(Integer)}

        ' Create a dynamic method with the name "Hello", a return type
        ' of Integer, and two parameters whose types are specified by
        ' the array helloArgs. Create the method in the module that
        ' defines the Test class.
        Dim hello As New DynamicMethod("Hello", _
            GetType(Integer), _
            helloArgs, _
            GetType(Test).Module)

        ' Create an array that specifies the parameter types of the
        ' overload of Console.WriteLine to be used in Hello.
        Dim writeStringArgs() As Type = {GetType(String)}
        ' Get the overload of Console.WriteLine that has one
        ' String parameter.
        Dim writeString As MethodInfo = GetType(Console). _
            GetMethod("WriteLine", writeStringArgs) 

        ' Get an ILGenerator and emit a body for the dynamic method.
        Dim il As ILGenerator = hello.GetILGenerator()
        ' Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0)
        ' Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, Nothing)
        ' The Hello method returns the value of the second argument;
        ' to do this, load the onto the stack and return.
        il.Emit(OpCodes.Ldarg_1)
        il.Emit(OpCodes.Ret)

        ' Create a delegate that represents the dynamic method. This
        ' action completes the method, and any further attempts to
        ' change the method will cause an exception.
    Dim hi As HelloInvoker = _
            hello.CreateDelegate(GetType(HelloInvoker))

        ' Use the delegate to execute the dynamic method. Save and
        ' print the return value.
        Dim retval As Integer = hi(vbCrLf & "Hello, World!", 42)
        Console.WriteLine("Executing delegate hi(""Hello, World!"", 42) returned " _
            & retval)

        ' Do it again, with different arguments.
        retval = hi(vbCrLf & "Hi, Mom!", 5280)
        Console.WriteLine("Executing delegate hi(""Hi, Mom!"", 5280) returned " _
            & retval)

        ' Create an array of arguments to use with the Invoke method.
        Dim invokeArgs() As Object = {vbCrLf & "Hello, World!", 42}
        ' Invoke the dynamic method using the arguments. This is much
        ' slower than using the delegate, because you must create an
        ' array to contain the arguments, and ValueType arguments
        ' must be boxed. Note that this overload of Invoke is 
        ' inherited from MethodBase, and simply calls the more 
        ' complete overload of Invoke.
        Dim objRet As Object = hello.Invoke(Nothing, invokeArgs)
        Console.WriteLine("hello.Invoke returned " & objRet)
    End Sub
End Class

' This code example produces the following output:
'
'Hello, World!
'Executing delegate hi("Hello, World!", 42) returned 42
'
'Hi, Mom!
'Executing delegate hi("Hi, Mom!", 5280) returned 5280
'
'Hello, World!
'hello.Invoke returned 42
'

注釈

このコンストラクターは、メソッド属性 MethodAttributes.PublicMethodAttributes.Staticを指定し、呼び出し規則 CallingConventions.Standardし、Just-In-Time (JIT) の可視性チェックをスキップしません。

このコンストラクターで作成された動的メソッドは、モジュール internalに含まれるすべての型のパブリックメンバーとFriendメンバー (Visual Basic ではm) にアクセスできます。

Note

下位互換性のために、このコンストラクターは、次の条件が両方とも当てはまる場合、SecurityPermission フラグを使用してSecurityPermissionFlag.ControlEvidenceを要求します。mは呼び出し元モジュール以外のモジュールであり、ReflectionPermission フラグを持つReflectionPermissionFlag.MemberAccessの要求は失敗しました。 SecurityPermissionの要求が成功した場合、操作は許可されます。

こちらもご覧ください

適用対象

DynamicMethod(String, Type, Type[], Type)

動的メソッドを作成し、メソッド名、戻り値の型、パラメーター型、および動的メソッドが論理的に関連付けられている型を指定します。

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * Type -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), owner As Type)

パラメーター

name
String

動的メソッドの名前。 長さ 0 の文字列を指定できますが、 nullすることはできません。

returnType
Type

動的メソッドの戻り値の型を指定する Type オブジェクト。メソッドに戻り値の型がない場合は null

parameterTypes
Type[]

動的メソッドのパラメーターの型を指定する Type オブジェクトの配列。メソッドにパラメーターがない場合は null

owner
Type

動的メソッドが論理的に関連付けられている Type 。 動的メソッドは、型のすべてのメンバーにアクセスできます。

例外

parameterTypesの要素がnullまたはVoidです。

-または-

owner は、インターフェイス、配列、オープン ジェネリック型、またはジェネリック型またはメソッドの型パラメーターです。

namenullです。

-または-

ownernullです。

.NET Framework と .NET Core バージョンが 2.1 より前の場合: returnType は、IsByReftrue を返す型です。

次のコード例では、型に論理的に関連付けられた DynamicMethod を作成します。 この関連付けにより、その型のプライベート メンバーにアクセスできます。

このコード例では、プライベート フィールドExampleという名前のクラス、最初のクラスから派生する DerivedFromExample という名前のクラス、UseLikeStaticを返し、Int32 型とExampleのパラメーターを持つ Int32 という名前のデリゲート型、および UseLikeInstance を返し、Int32型の 1 つのパラメーターを持つ Int32 という名前のデリゲート型を定義します。

次に、このコード例では、DynamicMethodのインスタンスのプライベート フィールドを変更し、前の値を返すExampleを作成します。

Note

一般に、クラスの内部フィールドを変更することは、オブジェクト指向のコーディング手法としては適していません。

このコード例では、 Example のインスタンスを作成し、次に 2 つのデリゲートを作成します。 1 つ目は、動的メソッドと同じパラメーターを持つ UseLikeStatic型です。 2 つ目は UseLikeInstance 型で、最初のパラメーター ( Example 型) がありません。 このデリゲートは、 CreateDelegate(Type, Object) メソッド オーバーロードを使用して作成されます。そのメソッド オーバーロードの 2 番目のパラメーターは、 Exampleのインスタンスです。この場合、作成したインスタンスは、新しく作成されたデリゲートにバインドされます。 そのデリゲートが呼び出されるたびに、動的メソッドは Exampleのバインドされたインスタンスに対して動作します。

Note

これは、.NET Framework 2.0 で導入されたデリゲート バインディングの緩和された規則と、 Delegate.CreateDelegate メソッドの新しいオーバーロードの例です。 詳細については、Delegate クラスを参照してください。

UseLikeStatic デリゲートが呼び出され、UseLikeInstance デリゲートにバインドされているExampleのインスタンスが渡されます。 その後、 UseLikeInstance デリゲートが呼び出され、両方のデリゲートが Exampleの同じインスタンスに対して動作します。 内部フィールドの値の変更は、各呼び出しの後に表示されます。 最後に、 UseLikeInstance デリゲートは DerivedFromExampleのインスタンスにバインドされ、デリゲート呼び出しが繰り返されます。

using System;
using System.Reflection;
using System.Reflection.Emit;

// These classes are for demonstration purposes.
//
public class Example
{
    private int id = 0;
    public Example(int id)
    {
        this.id = id;
    }
    public int ID { get { return id; }}
}

public class DerivedFromExample : Example
{
    public DerivedFromExample(int id) : base(id) {}
}

// Two delegates are declared: UseLikeInstance treats the dynamic
// method as if it were an instance method, and UseLikeStatic
// treats the dynamic method in the ordinary fashion.
//
public delegate int UseLikeInstance(int newID);
public delegate int UseLikeStatic(Example ex, int newID);

public class Demo
{
    public static void Main()
    {
        // This dynamic method changes the private id field. It has
        // no name; it returns the old id value (return type int);
        // it takes two parameters, an instance of Example and
        // an int that is the new value of id; and it is declared
        // with Example as the owner type, so it can access all
        // members, public and private.
        //
        DynamicMethod changeID = new DynamicMethod(
            "",
            typeof(int),
            new Type[] { typeof(Example), typeof(int) },
            typeof(Example)
        );

        // Get a FieldInfo for the private field 'id'.
        FieldInfo fid = typeof(Example).GetField(
            "id",
            BindingFlags.NonPublic | BindingFlags.Instance
        );

        ILGenerator ilg = changeID.GetILGenerator();

        // Push the current value of the id field onto the
        // evaluation stack. It's an instance field, so load the
        // instance of Example before accessing the field.
        ilg.Emit(OpCodes.Ldarg_0);
        ilg.Emit(OpCodes.Ldfld, fid);

        // Load the instance of Example again, load the new value
        // of id, and store the new field value.
        ilg.Emit(OpCodes.Ldarg_0);
        ilg.Emit(OpCodes.Ldarg_1);
        ilg.Emit(OpCodes.Stfld, fid);

        // The original value of the id field is now the only
        // thing on the stack, so return from the call.
        ilg.Emit(OpCodes.Ret);

        // Create a delegate that uses changeID in the ordinary
        // way, as a static method that takes an instance of
        // Example and an int.
        //
        UseLikeStatic uls =
            (UseLikeStatic) changeID.CreateDelegate(
                typeof(UseLikeStatic)
            );

        // Create an instance of Example with an id of 42.
        //
        Example ex = new Example(42);

        // Create a delegate that is bound to the instance of
        // of Example. This is possible because the first
        // parameter of changeID is of type Example. The
        // delegate has all the parameters of changeID except
        // the first.
        UseLikeInstance uli =
            (UseLikeInstance) changeID.CreateDelegate(
                typeof(UseLikeInstance),
                ex
            );

        // First, change the value of id by calling changeID as
        // a static method, passing in the instance of Example.
        //
        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uls(ex, 1492)
        );

        // Change the value of id again using the delegate bound
        // to the instance of Example.
        //
        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uli(2700)
        );

        Console.WriteLine("Final value of id: {0}", ex.ID);

        // Now repeat the process with a class that derives
        // from Example.
        //
        DerivedFromExample dfex = new DerivedFromExample(71);

        uli = (UseLikeInstance) changeID.CreateDelegate(
                typeof(UseLikeInstance),
                dfex
            );

        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uls(dfex, 73)
        );
        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uli(79)
        );
        Console.WriteLine("Final value of id: {0}", dfex.ID);
    }
}

/* This code example produces the following output:

Change the value of id; previous value: 42
Change the value of id; previous value: 1492
Final value of id: 2700
Change the value of id; previous value: 71
Change the value of id; previous value: 73
Final value of id: 79
 */
Imports System.Reflection
Imports System.Reflection.Emit

' These classes are for demonstration purposes.
'
Public Class Example
    Private _id As Integer = 0
    
    Public Sub New(ByVal newId As Integer) 
        _id = newId    
    End Sub
    
    Public ReadOnly Property ID() As Integer 
        Get
            Return _id
        End Get
    End Property 
End Class

Public Class DerivedFromExample
    Inherits Example
    
    Public Sub New(ByVal newId As Integer) 
        MyBase.New(newId)
    End Sub
End Class
 
' Two delegates are declared: UseLikeInstance treats the dynamic
' method as if it were an instance method, and UseLikeStatic
' treats the dynamic method in the ordinary fashion.
' 
Public Delegate Function UseLikeInstance(ByVal newID As Integer) _
    As Integer 
Public Delegate Function UseLikeStatic(ByVal ex As Example, _
    ByVal newID As Integer) As Integer 

Public Class Demo
    
    Public Shared Sub Main() 
        ' This dynamic method changes the private _id field. It 
        ' has no name; it returns the old _id value (return type 
        ' Integer); it takes two parameters, an instance of Example 
        ' and an Integer that is the new value of _id; and it is 
        ' declared with Example as the owner type, so it can 
        ' access all members, public and private.
        '
        Dim changeID As New DynamicMethod( _
            "", _
            GetType(Integer), _
            New Type() {GetType(Example), GetType(Integer)}, _
            GetType(Example) _
        )
        
        ' Get a FieldInfo for the private field '_id'.
        Dim fid As FieldInfo = GetType(Example).GetField( _
            "_id", _
            BindingFlags.NonPublic Or BindingFlags.Instance _
        )
        
        Dim ilg As ILGenerator = changeID.GetILGenerator()
        
        ' Push the current value of the id field onto the 
        ' evaluation stack. It's an instance field, so load the
        ' instance of Example before accessing the field.
        ilg.Emit(OpCodes.Ldarg_0)
        ilg.Emit(OpCodes.Ldfld, fid)
        
        ' Load the instance of Example again, load the new value 
        ' of id, and store the new field value. 
        ilg.Emit(OpCodes.Ldarg_0)
        ilg.Emit(OpCodes.Ldarg_1)
        ilg.Emit(OpCodes.Stfld, fid)
        
        ' The original value of the id field is now the only 
        ' thing on the stack, so return from the call.
        ilg.Emit(OpCodes.Ret)
        
        
        ' Create a delegate that uses changeID in the ordinary
        ' way, as a static method that takes an instance of
        ' Example and an Integer.
        '
        Dim uls As UseLikeStatic = CType( _
            changeID.CreateDelegate(GetType(UseLikeStatic)), _
            UseLikeStatic _
        )
        
        ' Create an instance of Example with an id of 42.
        '
        Dim ex As New Example(42)
        
        ' Create a delegate that is bound to the instance of 
        ' of Example. This is possible because the first 
        ' parameter of changeID is of type Example. The 
        ' delegate has all the parameters of changeID except
        ' the first.
        Dim uli As UseLikeInstance = CType( _
            changeID.CreateDelegate( _
                GetType(UseLikeInstance), _
                ex), _
            UseLikeInstance _
        )
        
        ' First, change the value of _id by calling changeID as
        ' a static method, passing in the instance of Example.
        '
        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uls(ex, 1492) _
        )
        
        ' Change the value of _id again using the delegate 
        ' bound to the instance of Example.
        '
        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uli(2700) _
        )
        
        Console.WriteLine("Final value of _id: {0}", ex.ID)
    

        ' Now repeat the process with a class that derives
        ' from Example.
        '
        Dim dfex As New DerivedFromExample(71)

        uli = CType( _
            changeID.CreateDelegate( _
                GetType(UseLikeInstance), _
                dfex), _
            UseLikeInstance _
        )

        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uls(dfex, 73) _
        )
        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uli(79) _
        )
        Console.WriteLine("Final value of _id: {0}", dfex.ID)

    End Sub
End Class

' This code example produces the following output:
'
'Change the value of _id; previous value: 42
'Change the value of _id; previous value: 1492
'Final value of _id: 2700
'Change the value of _id; previous value: 71
'Change the value of _id; previous value: 73
'Final value of _id: 79'

注釈

このコンストラクターで作成された動的メソッドは、owner型のすべてのメンバー、およびinternalを含むモジュール内の他のすべての型のパブリックメンバーとFriendメンバー (Visual Basic のowner) にアクセスできます。

このコンストラクターは、メソッド属性 MethodAttributes.PublicMethodAttributes.Staticを指定し、呼び出し規則 CallingConventions.Standardし、Just-In-Time (JIT) の可視性チェックをスキップしません。

Note

下位互換性のために、このコンストラクターは、次の条件が両方とも当てはまる場合、SecurityPermission フラグでSecurityPermissionFlag.ControlEvidenceを要求します。ownerは呼び出し元モジュール以外のモジュールにあり、ReflectionPermission フラグを持つReflectionPermissionFlag.MemberAccessの要求は失敗しました。 SecurityPermissionの要求が成功した場合、操作は許可されます。

こちらもご覧ください

適用対象

DynamicMethod(String, Type, Type[], Module, Boolean)

メソッド名、戻り値の型、パラメーター型、モジュール、および動的メソッドのMicrosoft中間言語 (MSIL) によってアクセスされる型とメンバーに対して Just-In-Time (JIT) 可視性チェックをスキップするかどうかを指定して、モジュールにグローバルな動的メソッドを作成します。

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m, bool skipVisibility);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, System.Reflection.Module m, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * System.Reflection.Module * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), m As Module, skipVisibility As Boolean)

パラメーター

name
String

動的メソッドの名前。 長さ 0 の文字列を指定できますが、 nullすることはできません。

returnType
Type

動的メソッドの戻り値の型を指定する Type オブジェクト。メソッドに戻り値の型がない場合は null

parameterTypes
Type[]

動的メソッドのパラメーターの型を指定する Type オブジェクトの配列。メソッドにパラメーターがない場合は null

m
Module

動的メソッドを論理的に関連付けるモジュールを表す Module

skipVisibility
Boolean

true 動的メソッドの MSIL によってアクセスされる型とメンバーに対する JIT 可視性チェックをスキップする場合。

例外

parameterTypesの要素がnullまたはVoidです。

-または-

m は、動的メソッドの匿名ホスティングを提供するモジュールです。

namenullです。

-または-

mnullです。

.NET Framework と .NET Core バージョンが 2.1 より前の場合: returnType は、IsByReftrue を返す型です。

注釈

このコンストラクターは、メソッド属性の MethodAttributes.PublicMethodAttributes.Static、および呼び出し規則 CallingConventions.Standardを指定します。

このコンストラクターで作成された動的メソッドは、含まれるモジュール m 内のすべての型の public および internal (Visual Basic の Friend) メンバーにアクセスできます。 JIT コンパイラの可視性チェックをスキップすると、動的メソッドは、他のすべての型のプライベートメンバーと保護されたメンバーにもアクセスできます。 これは、オブジェクトをシリアル化するコードを記述する場合などに便利です。

Note

下位互換性のために、このコンストラクターは、次の条件が両方とも当てはまる場合、SecurityPermission フラグを使用してSecurityPermissionFlag.ControlEvidenceを要求します。mは呼び出し元モジュール以外のモジュールであり、ReflectionPermission フラグを持つReflectionPermissionFlag.MemberAccessの要求は失敗しました。 SecurityPermissionの要求が成功した場合、操作は許可されます。

こちらもご覧ください

適用対象

DynamicMethod(String, Type, Type[], Type, Boolean)

動的メソッドを作成し、メソッド名、戻り値の型、パラメーター型、動的メソッドが論理的に関連付けられている型、および動的メソッドのMicrosoft中間言語 (MSIL) によってアクセスされる型とメンバーに対して Just-In-Time (JIT) 可視性チェックをスキップするかどうかを指定します。

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner, bool skipVisibility);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * Type * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), owner As Type, skipVisibility As Boolean)

パラメーター

name
String

動的メソッドの名前。 長さ 0 の文字列を指定できますが、 nullすることはできません。

returnType
Type

動的メソッドの戻り値の型を指定する Type オブジェクト。メソッドに戻り値の型がない場合は null

parameterTypes
Type[]

動的メソッドのパラメーターの型を指定する Type オブジェクトの配列。メソッドにパラメーターがない場合は null

owner
Type

動的メソッドが論理的に関連付けられている Type 。 動的メソッドは、型のすべてのメンバーにアクセスできます。

skipVisibility
Boolean

true 動的メソッドの MSIL によってアクセスされる型とメンバーに対する JIT 可視性チェックをスキップする場合。それ以外の場合は false

例外

parameterTypesの要素がnullまたはVoidです。

-または-

owner は、インターフェイス、配列、オープン ジェネリック型、またはジェネリック型またはメソッドの型パラメーターです。

namenullです。

-または-

ownernullです。

.NET Framework と .NET Core バージョンが 2.1 より前の場合: returnType は、IsByReftrue を返す型です。

注釈

このコンストラクターで作成された動的メソッドは、owner型のすべてのメンバー、およびinternalを含むモジュール内の他のすべての型のパブリックメンバーとFriendメンバー (Visual Basic のowner) にアクセスできます。 JIT コンパイラの可視性チェックをスキップすると、動的メソッドは、他のすべての型のプライベートメンバーと保護されたメンバーにもアクセスできます。 これは、オブジェクトをシリアル化するコードを記述する場合などに便利です。

このコンストラクターは、メソッド属性の MethodAttributes.PublicMethodAttributes.Static、および呼び出し規則 CallingConventions.Standardを指定します。

Note

下位互換性のために、このコンストラクターは、次の条件が両方とも当てはまる場合、SecurityPermission フラグでSecurityPermissionFlag.ControlEvidenceを要求します。ownerは呼び出し元モジュール以外のモジュールにあり、ReflectionPermission フラグを持つReflectionPermissionFlag.MemberAccessの要求は失敗しました。 SecurityPermissionの要求が成功した場合、操作は許可されます。

こちらもご覧ください

適用対象

DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Module, Boolean)

メソッド名、属性、呼び出し規則、戻り値の型、パラメーター型、モジュール、および動的メソッドのMicrosoft中間言語 (MSIL) によってアクセスされる型とメンバーに対して Just-In-Time (JIT) 可視性チェックをスキップするかどうかを指定して、モジュールにグローバルな動的メソッドを作成します。

public:
 DynamicMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m, bool skipVisibility);
public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Reflection.Module m, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Reflection.Module * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), m As Module, skipVisibility As Boolean)

パラメーター

name
String

動的メソッドの名前。 長さ 0 の文字列を指定できますが、 nullすることはできません。

attributes
MethodAttributes

動的メソッドの属性を指定する MethodAttributes 値のビットごとの組み合わせ。 使用できる組み合わせは、 PublicStaticのみです。

callingConvention
CallingConventions

動的メソッドの呼び出し規則。 Standardである必要があります。

returnType
Type

動的メソッドの戻り値の型を指定する Type オブジェクト。メソッドに戻り値の型がない場合は null

parameterTypes
Type[]

動的メソッドのパラメーターの型を指定する Type オブジェクトの配列。メソッドにパラメーターがない場合は null

m
Module

動的メソッドを論理的に関連付けるモジュールを表す Module

skipVisibility
Boolean

true 動的メソッドの MSIL によってアクセスされる型とメンバーに対する JIT 可視性チェックをスキップする場合。それ以外の場合は false

例外

parameterTypesの要素がnullまたはVoidです。

-または-

m は、動的メソッドの匿名ホスティングを提供するモジュールです。

namenullです。

-または-

mnullです。

attributes は、 PublicStatic以外のフラグの組み合わせです。

-または-

callingConventionStandardされていません。

-または-

returnType は、 IsByReftrueを返す型です。

注釈

このコンストラクターで作成された動的メソッドは、モジュール m に含まれるすべてのパブリックおよび内部型の public および internal (Visual Basic の Friend) メンバーにアクセスできます。

JIT コンパイラの可視性チェックをスキップすると、動的メソッドは、モジュール内の他のすべての型および他のすべてのアセンブリのプライベートメンバーと保護されたメンバーにもアクセスできます。 これは、オブジェクトをシリアル化するコードを記述する場合などに便利です。

Note

下位互換性のために、このコンストラクターは、次の条件が両方とも当てはまる場合、SecurityPermission フラグを使用してSecurityPermissionFlag.ControlEvidenceを要求します。mは呼び出し元モジュール以外のモジュールであり、ReflectionPermission フラグを持つReflectionPermissionFlag.MemberAccessの要求は失敗しました。 SecurityPermissionの要求が成功した場合、操作は許可されます。

こちらもご覧ください

適用対象

DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type, Boolean)

動的メソッドを作成し、メソッド名、属性、呼び出し規則、戻り値の型、パラメーター型、動的メソッドが論理的に関連付けられている型、および動的メソッドのMicrosoft中間言語 (MSIL) によってアクセスされる型とメンバーに対して Just-In-Time (JIT) 可視性チェックをスキップするかどうかを指定します。

public:
 DynamicMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner, bool skipVisibility);
public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * Type * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), owner As Type, skipVisibility As Boolean)

パラメーター

name
String

動的メソッドの名前。 長さ 0 の文字列を指定できますが、 nullすることはできません。

attributes
MethodAttributes

動的メソッドの属性を指定する MethodAttributes 値のビットごとの組み合わせ。 使用できる組み合わせは、 PublicStaticのみです。

callingConvention
CallingConventions

動的メソッドの呼び出し規則。 Standardである必要があります。

returnType
Type

動的メソッドの戻り値の型を指定する Type オブジェクト。メソッドに戻り値の型がない場合は null

parameterTypes
Type[]

動的メソッドのパラメーターの型を指定する Type オブジェクトの配列。メソッドにパラメーターがない場合は null

owner
Type

動的メソッドが論理的に関連付けられている Type 。 動的メソッドは、型のすべてのメンバーにアクセスできます。

skipVisibility
Boolean

true 動的メソッドの MSIL によってアクセスされる型とメンバーに対する JIT 可視性チェックをスキップする場合。それ以外の場合は false

例外

parameterTypesの要素がnullまたはVoidです。

-または-

owner は、インターフェイス、配列、オープン ジェネリック型、またはジェネリック型またはメソッドの型パラメーターです。

namenullです。

-または-

ownernullです。

attributes は、 PublicStatic以外のフラグの組み合わせです。

-または-

callingConventionStandardされていません。

-または-

returnType は、 IsByReftrueを返す型です。

注釈

動的メソッドは、 owner型を含むモジュールに対してグローバルです。 型 ownerのすべてのメンバーにアクセスできます。

このコンストラクターで作成された動的メソッドは、owner 型のすべてのメンバー、および internal (Visual Basic の場合は Friend) owner を含むモジュールに含まれるすべての型のメンバーにアクセスできます。 JIT コンパイラの可視性チェックをスキップすると、動的メソッドは、他のすべての型のプライベートメンバーと保護されたメンバーにもアクセスできます。 これは、オブジェクトをシリアル化するコードを記述する場合などに便利です。

Note

下位互換性のために、このコンストラクターは、次の条件が両方とも当てはまる場合、SecurityPermission フラグでSecurityPermissionFlag.ControlEvidenceを要求します。ownerは呼び出し元モジュール以外のモジュールにあり、ReflectionPermission フラグを持つReflectionPermissionFlag.MemberAccessの要求は失敗しました。 SecurityPermissionの要求が成功した場合、操作は許可されます。

こちらもご覧ください

適用対象