DynamicMethod コンストラクタ (String, MethodAttributes, CallingConventions, Type, Type[], Module, Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ name As String, _ attributes As MethodAttributes, _ callingConvention As CallingConventions, _ returnType As Type, _ parameterTypes As Type(), _ m As Module, _ skipVisibility As Boolean _ )
Dim name As String Dim attributes As MethodAttributes Dim callingConvention As CallingConventions Dim returnType As Type Dim parameterTypes As Type() Dim m As Module Dim skipVisibility As Boolean Dim instance As New DynamicMethod(name, attributes, callingConvention, returnType, parameterTypes, m, skipVisibility)
public DynamicMethod ( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility )
public: DynamicMethod ( String^ name, MethodAttributes attributes, CallingConventions callingConvention, Type^ returnType, array<Type^>^ parameterTypes, Module^ m, bool skipVisibility )
public DynamicMethod ( String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Module m, boolean skipVisibility )
public function DynamicMethod ( name : String, attributes : MethodAttributes, callingConvention : CallingConventions, returnType : Type, parameterTypes : Type[], m : Module, skipVisibility : boolean )

例外の種類 | 条件 |
---|---|
ArgumentException | parameterTypes の要素が null 参照 (Visual Basic では Nothing) または Void です。 |
ArgumentNullException | name が null 参照 (Visual Basic では Nothing) です。 または m が null 参照 (Visual Basic では Nothing) です。 |
NotSupportedException | attributes が Public と Static 以外のフラグの組み合わせです。 または callingConvention が Standard ではありません。 または |

このコンストラクタで作成した動的メソッドは、m モジュールに格納されたすべての型のパブリック メンバと internal (Visual Basic では Friend) メンバにアクセスできます。JIT コンパイラの参照範囲チェックをスキップすると、動的メソッドはモジュール内のすべての型のプライベート メンバとプロテクト メンバにもアクセスできるようになります。たとえば、これはオブジェクトをシリアル化するコードを記述する場合に役立ちます。

- ReflectionPermission (コードを出力するために必要なアクセス許可)。ReflectionPermissionFlag.ReflectionEmit (関連する列挙体)
- ReflectionPermission (skipVisibility が true の場合に、JIT の参照範囲チェックをスキップするために必要なアクセス許可)。ReflectionPermissionFlag.MemberAccess (関連する列挙体)
- SecurityPermission (呼び出し元のモジュール以外のモジュールに関連付けられている場合に、証拠を制御するために必要なアクセス許可)。SecurityPermissionFlag.ControlEvidence (関連する列挙体)

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


DynamicMethod コンストラクタ (String, MethodAttributes, CallingConventions, Type, Type[], Type, Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ name As String, _ attributes As MethodAttributes, _ callingConvention As CallingConventions, _ returnType As Type, _ parameterTypes As Type(), _ owner As Type, _ skipVisibility As Boolean _ )
Dim name As String Dim attributes As MethodAttributes Dim callingConvention As CallingConventions Dim returnType As Type Dim parameterTypes As Type() Dim owner As Type Dim skipVisibility As Boolean Dim instance As New DynamicMethod(name, attributes, callingConvention, returnType, parameterTypes, owner, skipVisibility)
public DynamicMethod ( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility )
public: DynamicMethod ( String^ name, MethodAttributes attributes, CallingConventions callingConvention, Type^ returnType, array<Type^>^ parameterTypes, Type^ owner, bool skipVisibility )
public DynamicMethod ( String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, boolean skipVisibility )
public function DynamicMethod ( name : String, attributes : MethodAttributes, callingConvention : CallingConventions, returnType : Type, parameterTypes : Type[], owner : Type, skipVisibility : boolean )

例外の種類 | 条件 |
---|---|
ArgumentException | parameterTypes の要素が null 参照 (Visual Basic では Nothing) または Void です。 または owner がインターフェイス、配列、オープン ジェネリック型、ジェネリック型またはジェネリック メソッドの型パラメータです。 |
ArgumentNullException | name が null 参照 (Visual Basic では Nothing) です。 または owner が null 参照 (Visual Basic では Nothing) です。 |
NotSupportedException | attributes が Public と Static 以外のフラグの組み合わせです。 または callingConvention が Standard ではありません。 または |

動的メソッドは、owner 型を格納するモジュールに対してグローバルです。動的メソッドは、owner 型のすべてのメンバにアクセスできます。
このコンストラクタで作成した動的メソッドは、owner 型のすべてのメンバ、および owner を格納するモジュールに格納されたすべての型のパブリック メンバと internal (Visual Basic では Friend) メンバにアクセスできます。JIT コンパイラの参照範囲チェックをスキップすると、動的メソッドはモジュール内の他のすべての型のプライベート メンバとプロテクト メンバにもアクセスできるようになります。たとえば、これはオブジェクトをシリアル化するコードを記述する場合に役立ちます。

- ReflectionPermission (コードを出力するために必要なアクセス許可)。ReflectionPermissionFlag.ReflectionEmit (関連する列挙体)
- ReflectionPermission (skipVisibility が true の場合に、JIT の参照範囲チェックをスキップするために必要なアクセス許可)。ReflectionPermissionFlag.MemberAccess (関連する列挙体)
- SecurityPermission (呼び出し元のモジュール以外のモジュールに関連付けられている場合に、証拠を制御するために必要なアクセス許可)。SecurityPermissionFlag.ControlEvidence (関連する列挙体)

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


DynamicMethod コンストラクタ (String, Type, Type[], Module, Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ name As String, _ returnType As Type, _ parameterTypes As Type(), _ m As Module, _ skipVisibility As Boolean _ )
Dim name As String Dim returnType As Type Dim parameterTypes As Type() Dim m As Module Dim skipVisibility As Boolean Dim instance As New DynamicMethod(name, returnType, parameterTypes, m, skipVisibility)
public DynamicMethod ( string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility )
public: DynamicMethod ( String^ name, Type^ returnType, array<Type^>^ parameterTypes, Module^ m, bool skipVisibility )
public DynamicMethod ( String name, Type returnType, Type[] parameterTypes, Module m, boolean skipVisibility )
public function DynamicMethod ( name : String, returnType : Type, parameterTypes : Type[], m : Module, skipVisibility : boolean )


このコンストラクタは、メソッド属性に MethodAttributes.Public と MethodAttributes.Static、呼び出し規約に CallingConventions.Standard を指定します。
このコンストラクタで作成した動的メソッドは、格納された m モジュール内のすべての型のパブリック メンバと internal (Visual Basic では Friend) メンバにアクセスできます。JIT コンパイラの参照範囲チェックをスキップすると、動的メソッドはモジュール内のすべての型のプライベート メンバとプロテクト メンバにもアクセスできるようになります。たとえば、これはオブジェクトをシリアル化するコードを記述する場合に役立ちます。

- ReflectionPermission (コードを出力するために必要なアクセス許可)。ReflectionPermissionFlag.ReflectionEmit (関連する列挙体)
- SecurityPermission (呼び出し元のモジュール以外のモジュールに関連付けられている場合に、証拠を制御するために必要なアクセス許可)。SecurityPermissionFlag.ControlEvidence (関連する列挙体)
- ReflectionPermission (skipVisibility が true の場合に、JIT の参照範囲チェックをスキップするために必要なアクセス許可)。ReflectionPermissionFlag.MemberAccess (関連する列挙体)

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


DynamicMethod コンストラクタ


DynamicMethod コンストラクタ (String, Type, Type[], Module)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ name As String, _ returnType As Type, _ parameterTypes As Type(), _ m As Module _ )
Dim name As String Dim returnType As Type Dim parameterTypes As Type() Dim m As Module Dim instance As New DynamicMethod(name, returnType, parameterTypes, m)
public function DynamicMethod ( name : String, returnType : Type, parameterTypes : Type[], m : Module )


このコンストラクタは、メソッド属性に MethodAttributes.Public と MethodAttributes.Static、呼び出し規約に CallingConventions.Standard を指定し、JIT (Just-In-Time) の参照範囲チェックをスキップしません。
このコンストラクタで作成した動的メソッドは、m モジュールに格納されたすべての型のパブリック メンバと internal (Visual Basic では Friend) メンバにアクセスできます。

2 つのパラメータを使用する動的メソッドを作成するコード例を次に示します。この例では、コンソールに 1 つ目のパラメータを出力する簡単な関数本体を出力し、2 つ目のパラメータをメソッドの戻り値として使用しています。この例では、デリゲートを作成することによってメソッドを完了し、さまざまなパラメータを持つデリゲートを呼び出し、最後に Invoke(Object,BindingFlags,Binder,Object[],CultureInfo) メソッドを使用して動的メソッドを呼び出します。
Imports System Imports System.Reflection Imports System.Reflection.Emit Imports Microsoft.VisualBasic 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 '
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); } }
using namespace System; using namespace System::Reflection; using namespace System::Reflection::Emit; public ref class Test { }; // Declare a delegate that will be used to execute the completed // dynamic method. delegate int HelloInvoker(String^ msg, int ret); int 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. array<Type^>^ helloArgs = {String::typeid, int::typeid}; // 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 = gcnew DynamicMethod("Hello", int::typeid, helloArgs, Test::typeid->Module); // Create an array that specifies the parameter types of the // overload of Console.WriteLine to be used in Hello. array<Type^>^ writeStringArgs = {String::typeid}; // Get the overload of Console.WriteLine that has one // String parameter. MethodInfo^ writeString = Console::typeid->GetMethod("WriteLine", writeStringArgs); // Get an ILGenerator and emit a body for the dynamic method. ILGenerator^ ilgen = hello->GetILGenerator(); // Load the first argument, which is a string, onto the stack. ilgen->Emit(OpCodes::Ldarg_0); // Call the overload of Console.WriteLine that prints a string. ilgen->EmitCall(OpCodes::Call, writeString, nullptr); // The Hello method returns the value of the second argument; // to do this, load the onto the stack and return. ilgen->Emit(OpCodes::Ldarg_1); ilgen->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^ helloDelegate = (HelloInvoker^) hello->CreateDelegate(HelloInvoker::typeid); // Use the delegate to execute the dynamic method. Save and // print the return value. int returnValue = helloDelegate("\r\nHello, World!", 42); Console::WriteLine("helloDelegate(\"Hello, World!\", 42) returned {0}", returnValue); // Do it again, with different arguments. returnValue = helloDelegate("\r\nHi, Mom!", 5280); Console::WriteLine("helloDelegate(\"Hi, Mom!\", 5280) returned {0}", returnValue); // Create an array of arguments to use with the Invoke method. array<Object^>^ delegateArgs = {"\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^ returnValueObject = hello->Invoke(nullptr, delegateArgs); Console::WriteLine("hello.Invoke returned {0}", returnValueObject); }
import System.*; import System.Reflection.*; import System.Reflection.Emit.*; import Microsoft.VisualBasic.*; public class Test { /** @delegate */ // 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(String[] args) { // 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[] = { String.class.ToType(), int.class.ToType() }; // 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", int.class.ToType(), helloArgs, Test.class.ToType().get_Module()); // Create an array that specifies the parameter types of the // overload of Console.WriteLine to be used in Hello. Type writeStringArgs[] = { String.class.ToType() }; // Get the overload of Console.WriteLine that has one // String parameter. MethodInfo writeString = Console.class.ToType().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( HelloInvoker.class.ToType())); // Use the delegate to execute the dynamic method. Save and // print the return value. int retval = hi.Invoke("\r\nHello, World!", 42); Console.WriteLine("Invoking delegate hi(\"Hello, World!\", 42) returned {0}", System.Convert.ToString(retval)); // Do it again, with different arguments. retval = hi.Invoke("\r\nHi, Mom!", 5280); Console.WriteLine("Invoking delegate hi(\"Hi, Mom!\", 5280) returned {0}", System.Convert.ToString(retval)); // Create an array of arguments to use with the Invoke method. Object invokeArgs[] = { "\r\nHello, World!", (System.Int32)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); } //main } //Test


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


DynamicMethod コンストラクタ (String, Type, Type[], Type, Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ name As String, _ returnType As Type, _ parameterTypes As Type(), _ owner As Type, _ skipVisibility As Boolean _ )
Dim name As String Dim returnType As Type Dim parameterTypes As Type() Dim owner As Type Dim skipVisibility As Boolean Dim instance As New DynamicMethod(name, returnType, parameterTypes, owner, skipVisibility)
public DynamicMethod ( string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility )
public: DynamicMethod ( String^ name, Type^ returnType, array<Type^>^ parameterTypes, Type^ owner, bool skipVisibility )
public DynamicMethod ( String name, Type returnType, Type[] parameterTypes, Type owner, boolean skipVisibility )
public function DynamicMethod ( name : String, returnType : Type, parameterTypes : Type[], owner : Type, skipVisibility : boolean )

例外の種類 | 条件 |
---|---|
ArgumentException | parameterTypes の要素が null 参照 (Visual Basic では Nothing) または Void です。 または owner がインターフェイス、配列、オープン ジェネリック型のいずれか、あるいはジェネリック型またはジェネリック メソッドの型パラメータです。 |
ArgumentNullException | name が null 参照 (Visual Basic では Nothing) です。 または owner が null 参照 (Visual Basic では Nothing) です。 |
NotSupportedException | returnType が null 参照 (Visual Basic では Nothing) であるか、IsByRef で true が返される型です。 |

このコンストラクタで作成した動的メソッドは、owner 型のすべてのメンバ、および owner を格納するモジュール内の他のすべての型のパブリック メンバと internal (Visual Basic では Friend) メンバにアクセスできます。JIT コンパイラの参照範囲チェックをスキップすると、動的メソッドはモジュール内の他のすべての型のプライベート メンバとプロテクト メンバにもアクセスできるようになります。たとえば、これはオブジェクトをシリアル化するコードを記述する場合に役立ちます。
このコンストラクタは、メソッド属性に MethodAttributes.Public と MethodAttributes.Static、呼び出し規約に CallingConventions.Standard を指定します。

- ReflectionPermission (コードを出力するために必要なアクセス許可)。ReflectionPermissionFlag.ReflectionEmit (関連する列挙体)
- SecurityPermission (呼び出し元のモジュール以外のモジュールに関連付けられている場合に、証拠を制御するために必要なアクセス許可)。SecurityPermissionFlag.ControlEvidence (関連する列挙体)
- ReflectionPermission (skipVisibility が true の場合に、JIT の参照範囲チェックをスキップするために必要なアクセス許可)。ReflectionPermissionFlag.MemberAccess (関連する列挙体)

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


DynamicMethod コンストラクタ (String, Type, Type[], Type)
アセンブリ: mscorlib (mscorlib.dll 内)

Public Sub New ( _ name As String, _ returnType As Type, _ parameterTypes As Type(), _ owner As Type _ )
Dim name As String Dim returnType As Type Dim parameterTypes As Type() Dim owner As Type Dim instance As New DynamicMethod(name, returnType, parameterTypes, owner)
public function DynamicMethod ( name : String, returnType : Type, parameterTypes : Type[], owner : Type )

例外の種類 | 条件 |
---|---|
ArgumentException | parameterTypes の要素が null 参照 (Visual Basic では Nothing) または Void です。 または owner がインターフェイス、配列、オープン ジェネリック型のいずれか、あるいはジェネリック型またはジェネリック メソッドの型パラメータです。 |
ArgumentNullException | name が null 参照 (Visual Basic では Nothing) です。 または owner が null 参照 (Visual Basic では Nothing) です。 |
NotSupportedException | returnType が null 参照 (Visual Basic では Nothing) であるか、IsByRef で true が返される型です。 |

このコンストラクタで作成した動的メソッドは、owner 型のすべてのメンバ、および owner を格納するモジュール内の他のすべての型のパブリック メンバと internal (Visual Basic では Friend) メンバにアクセスできます。
このコンストラクタは、メソッド属性に MethodAttributes.Public と MethodAttributes.Static、呼び出し規約に CallingConventions.Standard を指定し、JIT (Just-In-Time) の参照範囲チェックをスキップしません。

型に論理的に関連付けられた DynamicMethod を作成し、その型のプライベート メンバにアクセスできるようにするコード例を次に示します。
このコード例では、プライベート フィールドを持つ Example という名前のクラス、この最初のクラスから派生した DerivedFromxample という名前のクラス、Int32 を返し、Example 型と Int32 型のパラメータを持つ UseLikeStatic というデリゲート型、および Int32 を返し、Int32 型のパラメータを 1 つ持つ UseLikeInstance という名前のデリゲート型を定義します。
次に、Example のインスタンスのプライベート フィールドを変更し、以前の値を返す DynamicMethod を作成します。
![]() |
---|
この例のコードでは、Example のインスタンスを作成した後、2 つのデリゲートを作成しています。1 つ目は、動的メソッドと同じパラメータを持つ UseLikeStatic 型のデリゲートです。2 つ目は、1 つ目のパラメータ (Example 型) のない UseLikeInstance 型のデリゲートです。このデリゲートは、CreateDelegate(Type,Object) メソッド オーバーロードを使用して作成されます。このメソッド オーバーロードの 2 つ目のパラメータは Example のインスタンスです。この場合、インスタンスを作成するだけで新しく作成されたデリゲートにバインドされます。このデリゲートを呼び出すたびに、動的メソッドは Example のバインドされたインスタンスに対して機能します。
![]() |
---|
これは、System.Delegate.CreateDelegate メソッドの新しいオーバーロードと共に、.NET Framework Version 2.0 に導入されたデリゲート バインディングの緩やかな規則の一例です。詳細については、Delegate クラスのトピックを参照してください。 |
UseLikeStatic デリゲートが呼び出され、UseLikeInstance デリゲートにバインドされた Example のインスタンスが渡されます。次に、UseLikeInstance デリゲートが呼び出され、この 2 つのデリゲートが Example の同じインスタンスに対して機能します。内部フィールドの値の変更は、各呼び出しの後に表示されます。最後に、UseLikeInstance デリゲートが DerivedFromxample のインスタンスにバインドされ、デリゲートの呼び出しが繰り返されます。
Imports System 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'
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 */


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


- DynamicMethod コンストラクタのページへのリンク