MethodBuilder.CreateMethodBody(Byte[], Int32) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Создает тело метода с использованием предоставленного массива байтов инструкций промежуточного языка Майкрософт (MSIL).
public:
void CreateMethodBody(cli::array <System::Byte> ^ il, int count);
public void CreateMethodBody(byte[] il, int count);
member this.CreateMethodBody : byte[] * int -> unit
Public Sub CreateMethodBody (il As Byte(), count As Integer)
Параметры
- il
- Byte[]
Массив, содержащий допустимые инструкции MSIL. Если этот параметр равен null
, тело метода очищается.
- count
- Int32
Число допустимых байтов в массиве MSIL. Это значение игнорируется, если MSIL — null
.
Исключения
Значение count
выходит за пределы диапазона индексов предоставленного массива инструкций MSIL, и il
не равно null
.
Содержащий тип был создан ранее с помощью CreateType().
-или-
Этот метод был вызван ранее применительно к этому MethodBuilder
с аргументом il
, не равным null
.
-или-
Для текущего метода свойство IsGenericMethod имеет значение true
, но свойство IsGenericMethodDefinition имеет значение false
.
Примеры
В приведенном ниже примере простой метод, который добавляет два целых числа, создается с помощью кода операции с помощью CreateMethodBody
.
using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
class MethodBodyDemo {
// This class will demonstrate how to create a method body using
// the MethodBuilder.CreateMethodBody(byte[], int) method.
public static Type BuildDynType() {
Type addType = null;
AppDomain currentDom = Thread.GetDomain();
AssemblyName myAsmName = new AssemblyName();
myAsmName.Name = "MyDynamicAssembly";
AssemblyBuilder myAsmBldr = currentDom.DefineDynamicAssembly(
myAsmName,
AssemblyBuilderAccess.RunAndSave);
// The dynamic assembly space has been created. Next, create a module
// within it. The type Point will be reflected into this module.
ModuleBuilder myModuleBldr = myAsmBldr.DefineDynamicModule("MyModule");
TypeBuilder myTypeBldr = myModuleBldr.DefineType("Adder");
MethodBuilder myMthdBldr = myTypeBldr.DefineMethod("DoAdd",
MethodAttributes.Public |
MethodAttributes.Static,
typeof(int),
new Type[]
{typeof(int), typeof(int)});
// Build the array of Bytes holding the MSIL instructions.
byte[] ILcodes = new byte[] {
0x02, /* 02h is the opcode for ldarg.0 */
0x03, /* 03h is the opcode for ldarg.1 */
0x58, /* 58h is the opcode for add */
0x2A /* 2Ah is the opcode for ret */
};
myMthdBldr.CreateMethodBody(ILcodes, ILcodes.Length);
addType = myTypeBldr.CreateType();
return addType;
}
public static void Main() {
Type myType = BuildDynType();
Console.WriteLine("---");
Console.Write("Enter the first integer to add: ");
int aVal = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the second integer to add: ");
int bVal = Convert.ToInt32(Console.ReadLine());
object adderInst = Activator.CreateInstance(myType, new object[0]);
Console.WriteLine("The value of adding {0} to {1} is: {2}.",
aVal, bVal,
myType.InvokeMember("DoAdd",
BindingFlags.InvokeMethod,
null,
adderInst,
new object[] {aVal, bVal}));
}
}
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
_
Class MethodBodyDemo
' This class will demonstrate how to create a method body using
' the MethodBuilder.CreateMethodBody(byte[], int) method.
Public Shared Function BuildDynType() As Type
Dim addType As Type = Nothing
Dim currentDom As AppDomain = Thread.GetDomain()
Dim myAsmName As New AssemblyName()
myAsmName.Name = "MyDynamicAssembly"
Dim myAsmBldr As AssemblyBuilder = currentDom.DefineDynamicAssembly(myAsmName, _
AssemblyBuilderAccess.RunAndSave)
' The dynamic assembly space has been created. Next, create a module
' within it. The type Point will be reflected into this module.
Dim myModuleBldr As ModuleBuilder = myAsmBldr.DefineDynamicModule("MyModule")
Dim myTypeBldr As TypeBuilder = myModuleBldr.DefineType("Adder")
Dim myMthdBldr As MethodBuilder = myTypeBldr.DefineMethod("DoAdd", _
MethodAttributes.Public Or MethodAttributes.Static, _
GetType(Integer), _
New Type() {GetType(Integer), GetType(Integer)})
' Build the array of Bytes holding the MSIL instructions.
Dim ILcodes() As Byte = {&H2, &H3, &H58, &H2A}
' 02h is the opcode for ldarg.0
' 03h is the opcode for ldarg.1
' 58h is the opcode for add
' 2Ah is the opcode for ret
myMthdBldr.CreateMethodBody(ILcodes, ILcodes.Length)
addType = myTypeBldr.CreateType()
Return addType
End Function 'BuildDynType
Public Shared Sub Main()
Dim myType As Type = BuildDynType()
Console.WriteLine("---")
Console.Write("Enter the first integer to add: ")
Dim aVal As Integer = Convert.ToInt32(Console.ReadLine())
Console.Write("Enter the second integer to add: ")
Dim bVal As Integer = Convert.ToInt32(Console.ReadLine())
Dim adderInst As Object = Activator.CreateInstance(myType, New Object() {})
Console.WriteLine("The value of adding {0} to {1} is: {2}.", _
aVal, bVal, _
myType.InvokeMember("DoAdd", _
BindingFlags.InvokeMethod, _
Nothing, _
adderInst, _
New Object() {aVal, bVal}))
End Sub
End Class
Комментарии
Этот метод создает тело метода из il
массива , содержащего инструкции MSIL в виде кода операций. Число байтов допустимого MSIL задается по числу.
Примечание
В настоящее время это не полностью поддерживается. Пользователь не может указать расположение исправлений маркеров и обработчиков исключений.