DynamicMethod Konstruktor

Definisi

Membuat metode dinamis.

Overload

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

Menginisialisasi metode dinamis yang dihosting secara anonim, menentukan nama metode, jenis pengembalian, dan jenis parameter.

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

Menginisialisasi metode dinamis yang dihosting secara anonim, menentukan nama metode, jenis pengembalian, jenis parameter, dan apakah pemeriksaan visibilitas just-in-time (JIT) harus dilewati untuk jenis dan anggota yang diakses oleh Microsoft bahasa perantara (MSIL) dari metode dinamis.

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

Membuat metode dinamis yang bersifat global ke modul, menentukan nama metode, jenis pengembalian, jenis parameter, dan modul.

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

Membuat metode dinamis, menentukan nama metode, jenis pengembalian, jenis parameter, dan jenis yang terkait dengan metode dinamis secara logis.

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

Membuat metode dinamis yang bersifat global ke modul, menentukan nama metode, jenis pengembalian, jenis parameter, modul, dan apakah pemeriksaan visibilitas just-in-time (JIT) harus dilewati untuk jenis dan anggota yang diakses oleh Microsoft bahasa perantara (MSIL) dari metode dinamis.

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

Membuat metode dinamis, menentukan nama metode, jenis pengembalian, jenis parameter, jenis yang metode dinamisnya terkait secara logis, dan apakah pemeriksaan visibilitas just-in-time (JIT) harus dilewati untuk jenis dan anggota yang diakses oleh Microsoft bahasa perantara (MSIL) dari metode dinamis.

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

Membuat metode dinamis yang bersifat global ke modul, menentukan nama metode, atribut, konvensi panggilan, jenis pengembalian, jenis parameter, modul, dan apakah pemeriksaan visibilitas just-in-time (JIT) harus dilewati untuk jenis dan anggota yang diakses oleh Microsoft bahasa perantara (MSIL) dari metode dinamis.

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

Membuat metode dinamis, menentukan nama metode, atribut, konvensi panggilan, jenis pengembalian, jenis parameter, jenis yang metode dinamisnya terkait secara logis, dan apakah pemeriksaan visibilitas just-in-time (JIT) harus dilewati untuk jenis dan anggota yang diakses oleh bahasa perantara (MSIL) Microsoft dari metode dinamis.

DynamicMethod(String, Type, Type[])

Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs

Menginisialisasi metode dinamis yang dihosting secara anonim, menentukan nama metode, jenis pengembalian, dan jenis parameter.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")]
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes);
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes);
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")>]
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] -> System.Reflection.Emit.DynamicMethod
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type())

Parameter

name
String

Nama metode dinamis. Ini bisa berupa string panjang nol, tetapi tidak boleh null.

returnType
Type

Objek Type yang menentukan jenis pengembalian metode dinamis, atau null jika metode tidak memiliki jenis pengembalian.

parameterTypes
Type[]

Array Type objek yang menentukan jenis parameter metode dinamis, atau null jika metode tidak memiliki parameter.

Atribut

Pengecualian

Elemen dari parameterTypes adalah null atau Void.

name adalah null.

versi .NET Framework dan .NET Core yang lebih lama dari 2.1: returnType adalah jenis yang IsByRef mengembalikan true.

Keterangan

Metode dinamis yang dibuat oleh konstruktor ini dikaitkan dengan rakitan anonim alih-alih jenis atau modul yang ada. Rakitan anonim hanya ada untuk menyediakan lingkungan kotak pasir untuk metode dinamis, yaitu, untuk mengisolasinya dari kode lain. Lingkungan ini membuat metode dinamis dapat dihasilkan dan dijalankan dengan aman oleh kode dengan kepercayaan sebagian.

Konstruktor ini menentukan bahwa pemeriksaan visibilitas just-in-time (JIT) akan diberlakukan untuk bahasa perantara Microsoft (MSIL) dari metode dinamis. Artinya, kode dalam metode dinamis memiliki akses ke metode publik kelas publik. Pengecualian dilemparkan jika metode mencoba mengakses jenis atau anggota yang private, protected, atau internal (Friend di Visual Basic). Untuk membuat metode dinamis yang memiliki kemampuan terbatas untuk melewati pemeriksaan visibilitas JIT, gunakan DynamicMethod(String, Type, Type[], Boolean) konstruktor.

Ketika metode dinamis yang dihosting secara anonim dibangun, tumpukan panggilan rakitan pemancar disertakan. Ketika metode dipanggil, izin perakitan pemancaran digunakan alih-alih izin pemanggil aktual. Dengan demikian, metode dinamis tidak dapat dijalankan pada tingkat hak istimewa yang lebih tinggi daripada rakitan yang memancarkannya, bahkan jika diteruskan ke dan dijalankan oleh rakitan yang memiliki tingkat kepercayaan yang lebih tinggi.

Konstruktor ini menentukan atribut metode MethodAttributes.Public dan MethodAttributes.Static, serta konvensi panggilan CallingConventions.Standard.

Note

Konstruktor ini diperkenalkan dalam .NET Framework 3.5 atau yang lebih baru.

Lihat juga

Berlaku untuk

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

Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs

Menginisialisasi metode dinamis yang dihosting secara anonim, menentukan nama metode, jenis pengembalian, jenis parameter, dan apakah pemeriksaan visibilitas just-in-time (JIT) harus dilewati untuk jenis dan anggota yang diakses oleh Microsoft bahasa perantara (MSIL) dari metode dinamis.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, bool restrictedSkipVisibility);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")]
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, bool restrictedSkipVisibility);
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, bool restrictedSkipVisibility);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility);
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")>]
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * bool -> System.Reflection.Emit.DynamicMethod
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)

Parameter

name
String

Nama metode dinamis. Ini bisa berupa string panjang nol, tetapi tidak boleh null.

returnType
Type

Objek Type yang menentukan jenis pengembalian metode dinamis, atau null jika metode tidak memiliki jenis pengembalian.

parameterTypes
Type[]

Array Type objek yang menentukan jenis parameter metode dinamis, atau null jika metode tidak memiliki parameter.

restrictedSkipVisibility
Boolean

true untuk melewati pemeriksaan visibilitas JIT pada jenis dan anggota yang diakses oleh MSIL dari metode dinamis, dengan pembatasan ini: tingkat kepercayaan rakitan yang berisi jenis dan anggota tersebut harus sama dengan atau kurang dari tingkat kepercayaan tumpukan panggilan yang memancarkan metode dinamis; jika tidak, false.

Atribut

Pengecualian

Elemen dari parameterTypes adalah null atau Void.

name adalah null.

versi .NET Framework dan .NET Core yang lebih lama dari 2.1: returnType adalah jenis yang IsByRef mengembalikan true.

Keterangan

Metode dinamis yang dibuat oleh konstruktor ini dikaitkan dengan rakitan anonim alih-alih jenis atau modul yang ada. Rakitan anonim hanya ada untuk menyediakan lingkungan kotak pasir untuk metode dinamis, yaitu, untuk mengisolasinya dari kode lain. Lingkungan ini membuat metode dinamis dapat dihasilkan dan dijalankan dengan aman oleh kode dengan kepercayaan sebagian.

Metode dinamis yang dihosting secara anonim tidak memiliki akses otomatis ke jenis atau anggota apa pun yang private, protected, atau internal (Friend di Visual Basic). Ini berbeda dari metode dinamis yang terkait dengan jenis atau modul yang ada, yang memiliki akses ke anggota tersembunyi dalam cakupan terkait mereka.

Tentukan true untuk restrictedSkipVisibility jika metode dinamis Anda harus mengakses jenis atau anggota yang private, protected, atau internal. Ini memberikan metode dinamis akses terbatas ke anggota ini. Artinya, anggota hanya dapat diakses jika kondisi berikut terpenuhi:

  • Anggota target milik assembly yang memiliki tingkat kepercayaan yang sama dengan atau lebih rendah dari tumpukan panggilan yang memancarkan metode dinamis.

  • Tumpukan panggilan yang memancarkan metode dinamis ReflectionPermission diberikan flag ReflectionPermissionFlag.RestrictedMemberAccess. Ini selalu benar ketika kode dijalankan dengan kepercayaan penuh. Untuk kode tepercaya sebagian, itu benar hanya jika host secara eksplisit memberikan izin.

    Important

    Jika izin belum diberikan, pengecualian keamanan dilemparkan ketika CreateDelegate dipanggil atau ketika metode dinamis dipanggil, bukan ketika konstruktor ini dipanggil. Tidak ada izin khusus yang diperlukan untuk memancarkan metode dinamis.

Misalnya, metode dinamis yang dibuat dengan restrictedSkipVisibility diatur ke true dapat mengakses anggota privat dari assembly apa pun pada tumpukan panggilan jika tumpukan panggilan telah diberikan akses anggota terbatas. Jika metode dinamis dibuat dengan kode tepercaya sebagian pada tumpukan panggilan, metode ini tidak dapat mengakses anggota privat dari jenis dalam rakitan .NET Framework, karena rakitan tersebut sepenuhnya tepercaya.

Jika restrictedSkipVisibility adalah false, pemeriksaan visibilitas JIT diberlakukan. Kode dalam metode dinamis memiliki akses ke metode publik dari kelas publik, dan pengecualian dilemparkan jika mencoba mengakses jenis atau anggota yang private, protected, atau internal.

Ketika metode dinamis yang dihosting secara anonim dibangun, tumpukan panggilan rakitan pemancar disertakan. Ketika metode dipanggil, izin dari tumpukan panggilan yang memancarkan digunakan alih-alih izin dari pemanggil sebenarnya. Dengan demikian, metode dinamis tidak dapat dijalankan pada tingkat hak istimewa yang lebih tinggi daripada rakitan yang memancarkannya, bahkan jika diteruskan ke dan dijalankan oleh rakitan yang memiliki tingkat kepercayaan yang lebih tinggi.

Konstruktor ini menentukan atribut metode MethodAttributes.Public dan MethodAttributes.Static, serta konvensi panggilan CallingConventions.Standard.

Note

Konstruktor ini diperkenalkan dalam .NET Framework 3.5 atau yang lebih baru.

Lihat juga

Berlaku untuk

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

Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs

Membuat metode dinamis yang bersifat global ke modul, menentukan nama metode, jenis pengembalian, jenis parameter, dan modul.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")]
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, System.Reflection.Module m);
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, System.Reflection.Module m);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, System.Reflection.Module m);
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")>]
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * System.Reflection.Module -> System.Reflection.Emit.DynamicMethod
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)

Parameter

name
String

Nama metode dinamis. Ini bisa berupa string panjang nol, tetapi tidak boleh null.

returnType
Type

Objek Type yang menentukan jenis pengembalian metode dinamis, atau null jika metode tidak memiliki jenis pengembalian.

parameterTypes
Type[]

Array Type objek yang menentukan jenis parameter metode dinamis, atau null jika metode tidak memiliki parameter.

m
Module

mewakili Module modul yang metode dinamisnya akan dikaitkan secara logis.

Atribut

Pengecualian

Elemen dari parameterTypes adalah null atau Void.

-atau-

m adalah modul yang menyediakan hosting anonim untuk metode dinamis.

name adalah null.

-atau-

m adalah null.

versi .NET Framework dan .NET Core yang lebih lama dari 2.1: returnType adalah jenis yang IsByRef mengembalikan true.

Contoh

Contoh kode berikut membuat metode dinamis yang mengambil dua parameter. Contoh menghasilkan isi fungsi sederhana yang mencetak parameter pertama ke konsol, dan menggunakan parameter kedua sebagai nilai pengembalian dari metode tersebut. Contoh menyelesaikan metode dengan membuat delegasi, memanggil delegasi dengan parameter yang berbeda, dan akhirnya memanggil metode dinamis menggunakan metode .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
'

Keterangan

Konstruktor ini menentukan atribut MethodAttributes.Public metode dan MethodAttributes.Static, konvensi CallingConventions.Standardpanggilan , dan tidak melewati pemeriksaan visibilitas just-in-time (JIT).

Metode dinamis yang dibuat dengan konstruktor ini memiliki akses ke anggota publik dan internal (Friend dalam Visual Basic) dari semua jenis yang terkandung dalam modul m.

Note

Untuk kompatibilitas mundur, konstruktor ini memerlukan SecurityPermission dengan bendera SecurityPermissionFlag.ControlEvidence jika kondisi berikut keduanya benar: m adalah modul selain modul pemanggil, dan permintaan untuk ReflectionPermission dengan bendera ReflectionPermissionFlag.MemberAccess telah gagal. Jika permintaan SecurityPermission berhasil, operasi diizinkan.

Lihat juga

Berlaku untuk

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

Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs

Membuat metode dinamis, menentukan nama metode, jenis pengembalian, jenis parameter, dan jenis yang terkait dengan metode dinamis secara logis.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")]
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, Type owner);
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, Type owner);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner);
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")>]
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * Type -> System.Reflection.Emit.DynamicMethod
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)

Parameter

name
String

Nama metode dinamis. Ini bisa berupa string panjang nol, tetapi tidak boleh null.

returnType
Type

Objek Type yang menentukan jenis pengembalian metode dinamis, atau null jika metode tidak memiliki jenis pengembalian.

parameterTypes
Type[]

Array Type objek yang menentukan jenis parameter metode dinamis, atau null jika metode tidak memiliki parameter.

owner
Type

yang Type dengannya metode dinamis dikaitkan secara logis. Metode dinamis memiliki akses ke semua anggota jenis.

Atribut

Pengecualian

Elemen dari parameterTypes adalah null atau Void.

-atau-

owner adalah antarmuka, array, jenis generik terbuka, atau parameter jenis jenis atau metode generik.

name adalah null.

-atau-

owner adalah null.

versi .NET Framework dan .NET Core yang lebih lama dari 2.1: returnType adalah jenis yang IsByRef mengembalikan true.

Contoh

Contoh kode berikut membuat DynamicMethod yang secara logis terkait dengan jenis. Asosiasi ini memberinya akses ke anggota privat dari tipe tersebut.

Contoh kode mendefinisikan kelas bernama Example dengan bidang privat, kelas bernama DerivedFromExample yang berasal dari kelas pertama, jenis delegasi bernama UseLikeStatic yang mengembalikan Int32 dan memiliki parameter jenis Example dan Int32, dan jenis delegasi bernama UseLikeInstance yang mengembalikan Int32 dan memiliki satu parameter jenis Int32.

Kode contoh kemudian membuat DynamicMethod yang mengubah bidang privat dari instans Example dan mengembalikan nilai sebelumnya.

Note

Secara umum, mengubah bidang internal kelas bukanlah praktik pengkodean berorientasi objek yang baik.

Contoh kode membuat instans Example lalu membuat dua delegasi. Yang pertama adalah jenis UseLikeStatic, yang memiliki parameter yang sama dengan metode dinamis. Yang kedua adalah jenis UseLikeInstance, yang tidak memiliki parameter pertama (dari jenis Example). Delegasi ini dibuat menggunakan metode overload CreateDelegate(Type, Object); parameter kedua dari overload metode tersebut adalah instance Example, dalam hal ini instance yang baru saja dibuat, yang terikat pada delegasi yang baru dibuat. Setiap kali delegasi tersebut dipanggil, metode dinamis bertindak pada instans terikat dari Example.

Note

Ini adalah contoh aturan yang dilonggarkan untuk mendelegasikan pengikatan yang diperkenalkan dalam .NET Framework 2.0, bersama dengan kelebihan beban baru metode Delegate.CreateDelegate . Untuk informasi selengkapnya, lihat kelas Delegate.

UseLikeStatic Delegasi dipanggil, meneruskan instans Example yang terikat ke UseLikeInstance delegasi. UseLikeInstance Kemudian delegasi dipanggil, sehingga kedua delegasi bertindak pada instans yang sama dari Example. Perubahan nilai bidang data internal ditampilkan setelah setiap pemanggilan. Pada akhirnya, sebuah UseLikeInstance delegat diikat ke sebuah instans DerivedFromExample, dan panggilan delegat diulang.

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'

Keterangan

Metode dinamis yang dibuat dengan konstruktor ini memiliki akses ke semua anggota jenis owner, dan ke anggota publik dan internal (Friend dalam Visual Basic) dari semua jenis lain dalam modul yang berisi owner.

Konstruktor ini menentukan atribut MethodAttributes.Public metode dan MethodAttributes.Static, konvensi CallingConventions.Standardpanggilan , dan tidak melewati pemeriksaan visibilitas just-in-time (JIT).

Note

Untuk kompatibilitas mundur, konstruktor ini menuntut SecurityPermission dengan flag SecurityPermissionFlag.ControlEvidence jika kedua kondisi berikut benar: owner berada dalam modul selain modul pemanggil, dan permintaan untuk ReflectionPermission dengan bendera ReflectionPermissionFlag.MemberAccess telah gagal. Jika permintaan SecurityPermission berhasil, operasi diizinkan.

Lihat juga

Berlaku untuk

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

Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs

Membuat metode dinamis yang bersifat global ke modul, menentukan nama metode, jenis pengembalian, jenis parameter, modul, dan apakah pemeriksaan visibilitas just-in-time (JIT) harus dilewati untuk jenis dan anggota yang diakses oleh Microsoft bahasa perantara (MSIL) dari metode dinamis.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m, bool skipVisibility);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")]
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, System.Reflection.Module m, bool skipVisibility);
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, System.Reflection.Module m, bool skipVisibility);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, System.Reflection.Module m, bool skipVisibility);
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")>]
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * System.Reflection.Module * bool -> System.Reflection.Emit.DynamicMethod
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)

Parameter

name
String

Nama metode dinamis. Ini bisa berupa string panjang nol, tetapi tidak boleh null.

returnType
Type

Objek Type yang menentukan jenis pengembalian metode dinamis, atau null jika metode tidak memiliki jenis pengembalian.

parameterTypes
Type[]

Array Type objek yang menentukan jenis parameter metode dinamis, atau null jika metode tidak memiliki parameter.

m
Module

mewakili Module modul yang metode dinamisnya akan dikaitkan secara logis.

skipVisibility
Boolean

true untuk melewati pemeriksaan visibilitas JIT pada jenis dan anggota yang diakses oleh MSIL dari metode dinamis.

Atribut

Pengecualian

Elemen dari parameterTypes adalah null atau Void.

-atau-

m adalah modul yang menyediakan hosting anonim untuk metode dinamis.

name adalah null.

-atau-

m adalah null.

versi .NET Framework dan .NET Core yang lebih lama dari 2.1: returnType adalah jenis yang IsByRef mengembalikan true.

Keterangan

Konstruktor ini menentukan atribut MethodAttributes.Public metode dan MethodAttributes.Static, dan konvensi CallingConventions.Standardpanggilan .

Metode dinamis yang dibuat dengan konstruktor ini memiliki akses ke anggota publik dan internal (Friend di Visual Basic) dari semua jenis dalam modul yang terkandung m. Melompati pemeriksaan visibilitas kompilator JIT memungkinkan metode dinamis untuk mengakses anggota privat dan terlindungi dari semua jenis lainnya juga. Ini berguna, misalnya, saat menulis kode untuk membuat serialisasi objek.

Note

Untuk kompatibilitas mundur, konstruktor ini memerlukan SecurityPermission dengan bendera SecurityPermissionFlag.ControlEvidence jika kondisi berikut keduanya benar: m adalah modul selain modul pemanggil, dan permintaan untuk ReflectionPermission dengan bendera ReflectionPermissionFlag.MemberAccess telah gagal. Jika permintaan SecurityPermission berhasil, operasi diizinkan.

Lihat juga

Berlaku untuk

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

Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs

Membuat metode dinamis, menentukan nama metode, jenis pengembalian, jenis parameter, jenis yang metode dinamisnya terkait secara logis, dan apakah pemeriksaan visibilitas just-in-time (JIT) harus dilewati untuk jenis dan anggota yang diakses oleh Microsoft bahasa perantara (MSIL) dari metode dinamis.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner, bool skipVisibility);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")]
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, Type owner, bool skipVisibility);
public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, Type owner, bool skipVisibility);
public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility);
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")>]
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * Type * bool -> System.Reflection.Emit.DynamicMethod
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)

Parameter

name
String

Nama metode dinamis. Ini bisa berupa string panjang nol, tetapi tidak boleh null.

returnType
Type

Objek Type yang menentukan jenis pengembalian metode dinamis, atau null jika metode tidak memiliki jenis pengembalian.

parameterTypes
Type[]

Array Type objek yang menentukan jenis parameter metode dinamis, atau null jika metode tidak memiliki parameter.

owner
Type

yang Type dengannya metode dinamis dikaitkan secara logis. Metode dinamis memiliki akses ke semua anggota jenis.

skipVisibility
Boolean

true untuk melewati pemeriksaan visibilitas JIT pada jenis dan anggota yang diakses oleh MSIL dari metode dinamis; jika tidak, false.

Atribut

Pengecualian

Elemen dari parameterTypes adalah null atau Void.

-atau-

owner adalah antarmuka, array, jenis generik terbuka, atau parameter jenis jenis atau metode generik.

name adalah null.

-atau-

owner adalah null.

versi .NET Framework dan .NET Core yang lebih lama dari 2.1: returnType adalah jenis yang IsByRef mengembalikan true.

Keterangan

Metode dinamis yang dibuat dengan konstruktor ini memiliki akses ke semua anggota jenis owner, dan ke anggota publik dan internal (Friend dalam Visual Basic) dari semua jenis lain dalam modul yang berisi owner. Melompati pemeriksaan visibilitas kompilator JIT memungkinkan metode dinamis untuk mengakses anggota privat dan terlindungi dari semua jenis lainnya juga. Ini berguna, misalnya, saat menulis kode untuk membuat serialisasi objek.

Konstruktor ini menentukan atribut MethodAttributes.Public metode dan MethodAttributes.Static, dan konvensi CallingConventions.Standardpanggilan .

Note

Untuk kompatibilitas mundur, konstruktor ini menuntut SecurityPermission dengan flag SecurityPermissionFlag.ControlEvidence jika kedua kondisi berikut benar: owner berada dalam modul selain modul pemanggil, dan permintaan untuk ReflectionPermission dengan bendera ReflectionPermissionFlag.MemberAccess telah gagal. Jika permintaan SecurityPermission berhasil, operasi diizinkan.

Lihat juga

Berlaku untuk

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

Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs

Membuat metode dinamis yang bersifat global ke modul, menentukan nama metode, atribut, konvensi panggilan, jenis pengembalian, jenis parameter, modul, dan apakah pemeriksaan visibilitas just-in-time (JIT) harus dilewati untuk jenis dan anggota yang diakses oleh Microsoft bahasa perantara (MSIL) dari metode dinamis.

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);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")]
public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, 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);
public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Reflection.Module m, bool skipVisibility);
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")>]
new System.Reflection.Emit.DynamicMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Reflection.Module * bool -> System.Reflection.Emit.DynamicMethod
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)

Parameter

name
String

Nama metode dinamis. Ini bisa berupa string panjang nol, tetapi tidak boleh null.

attributes
MethodAttributes

Kombinasi bitwise dari MethodAttributes nilai yang menentukan atribut metode dinamis. Satu-satunya kombinasi yang diizinkan adalah Public dan Static.

callingConvention
CallingConventions

Konvensi panggilan untuk metode dinamis. Harus berupa Standard .

returnType
Type

Objek Type yang menentukan jenis pengembalian metode dinamis, atau null jika metode tidak memiliki jenis pengembalian.

parameterTypes
Type[]

Array Type objek yang menentukan jenis parameter metode dinamis, atau null jika metode tidak memiliki parameter.

m
Module

mewakili Module modul yang metode dinamisnya akan dikaitkan secara logis.

skipVisibility
Boolean

true untuk melewati pemeriksaan visibilitas JIT pada jenis dan anggota yang diakses oleh MSIL dari metode dinamis; jika tidak, false.

Atribut

Pengecualian

Elemen dari parameterTypes adalah null atau Void.

-atau-

m adalah modul yang menyediakan hosting anonim untuk metode dinamis.

name adalah null.

-atau-

m adalah null.

attributes adalah kombinasi bendera selain Public dan Static.

-atau-

callingConvention bukan Standard.

-atau-

returnType adalah jenis yang IsByRef mengembalikan true.

Keterangan

Metode dinamis yang dibuat dengan konstruktor ini memiliki akses ke anggota publik dan internal (Friend di Visual Basic) dari semua jenis publik dan internal yang terkandung dalam modul m.

Melompati pemeriksaan visibilitas kompilator JIT memungkinkan metode dinamis untuk mengakses anggota privat dan terlindungi dari semua jenis lain dalam modul dan di semua rakitan lainnya juga. Ini berguna, misalnya, saat menulis kode untuk membuat serialisasi objek.

Note

Untuk kompatibilitas mundur, konstruktor ini memerlukan SecurityPermission dengan bendera SecurityPermissionFlag.ControlEvidence jika kondisi berikut keduanya benar: m adalah modul selain modul pemanggil, dan permintaan untuk ReflectionPermission dengan bendera ReflectionPermissionFlag.MemberAccess telah gagal. Jika permintaan SecurityPermission berhasil, operasi diizinkan.

Lihat juga

Berlaku untuk

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

Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs
Sumber:
DynamicMethod.cs

Membuat metode dinamis, menentukan nama metode, atribut, konvensi panggilan, jenis pengembalian, jenis parameter, jenis yang metode dinamisnya terkait secara logis, dan apakah pemeriksaan visibilitas just-in-time (JIT) harus dilewati untuk jenis dan anggota yang diakses oleh bahasa perantara (MSIL) Microsoft dari metode dinamis.

public:
 DynamicMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner, bool skipVisibility);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")]
public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, 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);
public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility);
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a DynamicMethod requires dynamic code.")>]
new System.Reflection.Emit.DynamicMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * Type * bool -> System.Reflection.Emit.DynamicMethod
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)

Parameter

name
String

Nama metode dinamis. Ini bisa berupa string panjang nol, tetapi tidak boleh null.

attributes
MethodAttributes

Kombinasi bitwise dari MethodAttributes nilai yang menentukan atribut metode dinamis. Satu-satunya kombinasi yang diizinkan adalah Public dan Static.

callingConvention
CallingConventions

Konvensi panggilan untuk metode dinamis. Harus berupa Standard .

returnType
Type

Objek Type yang menentukan jenis pengembalian metode dinamis, atau null jika metode tidak memiliki jenis pengembalian.

parameterTypes
Type[]

Array Type objek yang menentukan jenis parameter metode dinamis, atau null jika metode tidak memiliki parameter.

owner
Type

yang Type dengannya metode dinamis dikaitkan secara logis. Metode dinamis memiliki akses ke semua anggota jenis.

skipVisibility
Boolean

true untuk melewati pemeriksaan visibilitas JIT pada jenis dan anggota yang diakses oleh MSIL dari metode dinamis; jika tidak, false.

Atribut

Pengecualian

Elemen dari parameterTypes adalah null atau Void.

-atau-

owner adalah antarmuka, array, jenis generik terbuka, atau parameter jenis jenis atau metode generik.

name adalah null.

-atau-

owner adalah null.

attributes adalah kombinasi bendera selain Public dan Static.

-atau-

callingConvention bukan Standard.

-atau-

returnType adalah jenis yang IsByRef mengembalikan true.

Keterangan

Metode dinamis bersifat global untuk modul yang berisi jenis owner. Ini memiliki akses ke semua anggota jenis owner.

Metode dinamis yang dibuat dengan konstruktor ini memiliki akses ke semua anggota jenis owner, dan untuk publik dan internal (Friend di Visual Basic) anggota semua jenis yang terkandung dalam modul yang berisi owner. Melompati pemeriksaan visibilitas kompilator JIT memungkinkan metode dinamis untuk mengakses anggota privat dan terlindungi dari semua jenis lainnya juga. Ini berguna, misalnya, saat menulis kode untuk membuat serialisasi objek.

Note

Untuk kompatibilitas mundur, konstruktor ini menuntut SecurityPermission dengan flag SecurityPermissionFlag.ControlEvidence jika kedua kondisi berikut benar: owner berada dalam modul selain modul pemanggil, dan permintaan untuk ReflectionPermission dengan bendera ReflectionPermissionFlag.MemberAccess telah gagal. Jika permintaan SecurityPermission berhasil, operasi diizinkan.

Lihat juga

Berlaku untuk