Прочитать на английском

Поделиться через


DynamicMethod.GetILGenerator Метод

Определение

Возвращает генератор MSIL, который может использоваться для создания тела динамического метода.

Перегрузки

GetILGenerator(Int32)

Возвращает генератор промежуточного языка Майкрософт (MSIL) для этого метода с указанным размером потока MSIL.

GetILGenerator()

Возвращает генератор MSIL для этого метода с размером потока MSIL, по умолчанию равным 64 байтам.

GetILGenerator(Int32)

Исходный код:
DynamicMethod.CoreCLR.cs
Исходный код:
DynamicMethod.cs
Исходный код:
DynamicMethod.CoreCLR.cs
Исходный код:
DynamicMethod.CoreCLR.cs

Возвращает генератор промежуточного языка Майкрософт (MSIL) для этого метода с указанным размером потока MSIL.

public System.Reflection.Emit.ILGenerator GetILGenerator(int streamSize);

Параметры

streamSize
Int32

Размер потока MSIL (в байтах).

Возвращаемое значение

Объект ILGenerator для метода с указанным размером потока MSIL.

Примеры

В следующем примере кода демонстрируется перегрузка этого метода. Этот пример входит в состав более крупного примера использования класса DynamicMethod.

// 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,
// using a stream size larger than the IL that will be
// emitted.
ILGenerator il = hello.GetILGenerator(256);
// 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);

Комментарии

После завершения динамического метода путем вызова CreateDelegate метода или Invoke любая дальнейшая попытка добавления MSIL игнорируется. Исключение не выдается.

Примечание

В динамических методах существуют ограничения на непроверяемый код, даже в некоторых сценариях с полным доверием. См. подраздел "Проверка" в разделе примечаний для DynamicMethod.

См. также раздел

Применяется к

.NET 10 и другие версии
Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided), 2.1

GetILGenerator()

Исходный код:
DynamicMethod.cs
Исходный код:
DynamicMethod.cs
Исходный код:
DynamicMethod.cs
Исходный код:
DynamicMethod.cs

Возвращает генератор MSIL для этого метода с размером потока MSIL, по умолчанию равным 64 байтам.

public System.Reflection.Emit.ILGenerator GetILGenerator();

Возвращаемое значение

Объект ILGenerator для метода.

Примеры

В следующем примере кода создается динамический метод, который принимает два параметра. В примере создается простая функция, которая выводит первый параметр в консоль, а второй параметр используется в качестве возвращаемого значения метода. В примере метод завершается путем создания делегата, вызывается делегат с разными параметрами и, наконец, вызывается динамический метод с помощью Invoke метода .

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);
    }
}

Комментарии

После завершения динамического метода путем вызова CreateDelegate метода или Invoke любая дальнейшая попытка добавления MSIL игнорируется. Исключение не выдается.

Примечание

В динамических методах существуют ограничения на непроверяемый код, даже в некоторых сценариях с полным доверием. См. подраздел "Проверка" в разделе примечаний для DynamicMethod.

См. также раздел

Применяется к

.NET 10 и другие версии
Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided), 2.1