AssemblyBuilder Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Defines and represents a dynamic assembly.
public ref class AssemblyBuilder sealed : System::Reflection::Assembly
public ref class AssemblyBuilder abstract : System::Reflection::Assembly
public ref class AssemblyBuilder sealed : System::Reflection::Assembly, System::Runtime::InteropServices::_AssemblyBuilder
public sealed class AssemblyBuilder : System.Reflection.Assembly
public abstract class AssemblyBuilder : System.Reflection.Assembly
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
public sealed class AssemblyBuilder : System.Reflection.Assembly, System.Runtime.InteropServices._AssemblyBuilder
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyBuilder : System.Reflection.Assembly, System.Runtime.InteropServices._AssemblyBuilder
type AssemblyBuilder = class
inherit Assembly
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
type AssemblyBuilder = class
inherit Assembly
interface _AssemblyBuilder
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type AssemblyBuilder = class
inherit Assembly
interface _AssemblyBuilder
Public NotInheritable Class AssemblyBuilder
Inherits Assembly
Public MustInherit Class AssemblyBuilder
Inherits Assembly
Public NotInheritable Class AssemblyBuilder
Inherits Assembly
Implements _AssemblyBuilder
- Inheritance
- Derived
- Attributes
- Implements
Examples
The following code example shows how to define and use a dynamic assembly. The example assembly contains one type, MyDynamicType
, that has a private field, a property that gets and sets the private field, constructors that initialize the private field, and a method that multiplies a user-supplied number by the private field value and returns the result.
using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void main()
{
// This code creates an assembly that contains one type,
// named "MyDynamicType", that has a private field, a property
// that gets and sets the private field, constructors that
// initialize the private field, and a method that multiplies
// a user-supplied number by the private field value and returns
// the result. In Visual C++ the type might look like this:
/*
public ref class MyDynamicType
{
private:
int m_number;
public:
MyDynamicType() : m_number(42) {};
MyDynamicType(int initNumber) : m_number(initNumber) {};
property int Number
{
int get() { return m_number; }
void set(int value) { m_number = value; }
}
int MyMethod(int multiplier)
{
return m_number * multiplier;
}
};
*/
AssemblyName^ aName = gcnew AssemblyName("DynamicAssemblyExample");
AssemblyBuilder^ ab =
AssemblyBuilder::DefineDynamicAssembly(
aName,
AssemblyBuilderAccess::Run);
// The module name is usually the same as the assembly name
ModuleBuilder^ mb =
ab->DefineDynamicModule(aName->Name);
TypeBuilder^ tb = mb->DefineType(
"MyDynamicType",
TypeAttributes::Public);
// Add a private field of type int (Int32).
FieldBuilder^ fbNumber = tb->DefineField(
"m_number",
int::typeid,
FieldAttributes::Private);
// Define a constructor that takes an integer argument and
// stores it in the private field.
array<Type^>^ parameterTypes = { int::typeid };
ConstructorBuilder^ ctor1 = tb->DefineConstructor(
MethodAttributes::Public,
CallingConventions::Standard,
parameterTypes);
ILGenerator^ ctor1IL = ctor1->GetILGenerator();
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before calling the base
// class constructor. Specify the default constructor of the
// base class (System::Object) by passing an empty array of
// types (Type::EmptyTypes) to GetConstructor.
ctor1IL->Emit(OpCodes::Ldarg_0);
ctor1IL->Emit(OpCodes::Call,
Object::typeid->GetConstructor(Type::EmptyTypes));
// Push the instance on the stack before pushing the argument
// that is to be assigned to the private field m_number.
ctor1IL->Emit(OpCodes::Ldarg_0);
ctor1IL->Emit(OpCodes::Ldarg_1);
ctor1IL->Emit(OpCodes::Stfld, fbNumber);
ctor1IL->Emit(OpCodes::Ret);
// Define a default constructor that supplies a default value
// for the private field. For parameter types, pass the empty
// array of types or pass nullptr.
ConstructorBuilder^ ctor0 = tb->DefineConstructor(
MethodAttributes::Public,
CallingConventions::Standard,
Type::EmptyTypes);
ILGenerator^ ctor0IL = ctor0->GetILGenerator();
ctor0IL->Emit(OpCodes::Ldarg_0);
ctor0IL->Emit(OpCodes::Call,
Object::typeid->GetConstructor(Type::EmptyTypes));
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before pushing the default
// value on the stack.
ctor0IL->Emit(OpCodes::Ldarg_0);
ctor0IL->Emit(OpCodes::Ldc_I4_S, 42);
ctor0IL->Emit(OpCodes::Stfld, fbNumber);
ctor0IL->Emit(OpCodes::Ret);
// Define a property named Number that gets and sets the private
// field.
//
// The last argument of DefineProperty is nullptr, because the
// property has no parameters. (If you don't specify nullptr, you must
// specify an array of Type objects. For a parameterless property,
// use the built-in array with no elements: Type::EmptyTypes)
PropertyBuilder^ pbNumber = tb->DefineProperty(
"Number",
PropertyAttributes::HasDefault,
int::typeid,
nullptr);
// The property "set" and property "get" methods require a special
// set of attributes.
MethodAttributes getSetAttr = MethodAttributes::Public |
MethodAttributes::SpecialName | MethodAttributes::HideBySig;
// Define the "get" accessor method for Number. The method returns
// an integer and has no arguments. (Note that nullptr could be
// used instead of Types::EmptyTypes)
MethodBuilder^ mbNumberGetAccessor = tb->DefineMethod(
"get_Number",
getSetAttr,
int::typeid,
Type::EmptyTypes);
ILGenerator^ numberGetIL = mbNumberGetAccessor->GetILGenerator();
// For an instance property, argument zero is the instance. Load the
// instance, then load the private field and return, leaving the
// field value on the stack.
numberGetIL->Emit(OpCodes::Ldarg_0);
numberGetIL->Emit(OpCodes::Ldfld, fbNumber);
numberGetIL->Emit(OpCodes::Ret);
// Define the "set" accessor method for Number, which has no return
// type and takes one argument of type int (Int32).
MethodBuilder^ mbNumberSetAccessor = tb->DefineMethod(
"set_Number",
getSetAttr,
nullptr,
gcnew array<Type^> { int::typeid });
ILGenerator^ numberSetIL = mbNumberSetAccessor->GetILGenerator();
// Load the instance and then the numeric argument, then store the
// argument in the field.
numberSetIL->Emit(OpCodes::Ldarg_0);
numberSetIL->Emit(OpCodes::Ldarg_1);
numberSetIL->Emit(OpCodes::Stfld, fbNumber);
numberSetIL->Emit(OpCodes::Ret);
// Last, map the "get" and "set" accessor methods to the
// PropertyBuilder. The property is now complete.
pbNumber->SetGetMethod(mbNumberGetAccessor);
pbNumber->SetSetMethod(mbNumberSetAccessor);
// Define a method that accepts an integer argument and returns
// the product of that integer and the private field m_number. This
// time, the array of parameter types is created on the fly.
MethodBuilder^ meth = tb->DefineMethod(
"MyMethod",
MethodAttributes::Public,
int::typeid,
gcnew array<Type^> { int::typeid });
ILGenerator^ methIL = meth->GetILGenerator();
// To retrieve the private instance field, load the instance it
// belongs to (argument zero). After loading the field, load the
// argument one and then multiply. Return from the method with
// the return value (the product of the two numbers) on the
// execution stack.
methIL->Emit(OpCodes::Ldarg_0);
methIL->Emit(OpCodes::Ldfld, fbNumber);
methIL->Emit(OpCodes::Ldarg_1);
methIL->Emit(OpCodes::Mul);
methIL->Emit(OpCodes::Ret);
// Finish the type->
Type^ t = tb->CreateType();
// Because AssemblyBuilderAccess includes Run, the code can be
// executed immediately. Start by getting reflection objects for
// the method and the property.
MethodInfo^ mi = t->GetMethod("MyMethod");
PropertyInfo^ pi = t->GetProperty("Number");
// Create an instance of MyDynamicType using the default
// constructor.
Object^ o1 = Activator::CreateInstance(t);
// Display the value of the property, then change it to 127 and
// display it again. Use nullptr to indicate that the property
// has no index.
Console::WriteLine("o1->Number: {0}", pi->GetValue(o1, nullptr));
pi->SetValue(o1, 127, nullptr);
Console::WriteLine("o1->Number: {0}", pi->GetValue(o1, nullptr));
// Call MyMethod, passing 22, and display the return value, 22
// times 127. Arguments must be passed as an array, even when
// there is only one.
array<Object^>^ arguments = { 22 };
Console::WriteLine("o1->MyMethod(22): {0}",
mi->Invoke(o1, arguments));
// Create an instance of MyDynamicType using the constructor
// that specifies m_Number. The constructor is identified by
// matching the types in the argument array. In this case,
// the argument array is created on the fly. Display the
// property value.
Object^ o2 = Activator::CreateInstance(t,
gcnew array<Object^> { 5280 });
Console::WriteLine("o2->Number: {0}", pi->GetValue(o2, nullptr));
};
/* This code produces the following output:
o1->Number: 42
o1->Number: 127
o1->MyMethod(22): 2794
o2->Number: 5280
*/
using System;
using System.Reflection;
using System.Reflection.Emit;
class DemoAssemblyBuilder
{
public static void Main()
{
// This code creates an assembly that contains one type,
// named "MyDynamicType", that has a private field, a property
// that gets and sets the private field, constructors that
// initialize the private field, and a method that multiplies
// a user-supplied number by the private field value and returns
// the result. In C# the type might look like this:
/*
public class MyDynamicType
{
private int m_number;
public MyDynamicType() : this(42) {}
public MyDynamicType(int initNumber)
{
m_number = initNumber;
}
public int Number
{
get { return m_number; }
set { m_number = value; }
}
public int MyMethod(int multiplier)
{
return m_number * multiplier;
}
}
*/
var aName = new AssemblyName("DynamicAssemblyExample");
AssemblyBuilder ab =
AssemblyBuilder.DefineDynamicAssembly(
aName,
AssemblyBuilderAccess.Run);
// The module name is usually the same as the assembly name.
ModuleBuilder mb = ab.DefineDynamicModule(aName.Name ?? "DynamicAssemblyExample");
TypeBuilder tb = mb.DefineType(
"MyDynamicType",
TypeAttributes.Public);
// Add a private field of type int (Int32).
FieldBuilder fbNumber = tb.DefineField(
"m_number",
typeof(int),
FieldAttributes.Private);
// Define a constructor that takes an integer argument and
// stores it in the private field.
Type[] parameterTypes = { typeof(int) };
ConstructorBuilder ctor1 = tb.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
parameterTypes);
ILGenerator ctor1IL = ctor1.GetILGenerator();
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before calling the base
// class constructor. Specify the default constructor of the
// base class (System.Object) by passing an empty array of
// types (Type.EmptyTypes) to GetConstructor.
ctor1IL.Emit(OpCodes.Ldarg_0);
ConstructorInfo? ci = typeof(object).GetConstructor(Type.EmptyTypes);
ctor1IL.Emit(OpCodes.Call, ci!);
// Push the instance on the stack before pushing the argument
// that is to be assigned to the private field m_number.
ctor1IL.Emit(OpCodes.Ldarg_0);
ctor1IL.Emit(OpCodes.Ldarg_1);
ctor1IL.Emit(OpCodes.Stfld, fbNumber);
ctor1IL.Emit(OpCodes.Ret);
// Define a default constructor that supplies a default value
// for the private field. For parameter types, pass the empty
// array of types or pass null.
ConstructorBuilder ctor0 = tb.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
Type.EmptyTypes);
ILGenerator ctor0IL = ctor0.GetILGenerator();
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before pushing the default
// value on the stack, then call constructor ctor1.
ctor0IL.Emit(OpCodes.Ldarg_0);
ctor0IL.Emit(OpCodes.Ldc_I4_S, 42);
ctor0IL.Emit(OpCodes.Call, ctor1);
ctor0IL.Emit(OpCodes.Ret);
// Define a property named Number that gets and sets the private
// field.
//
// The last argument of DefineProperty is null, because the
// property has no parameters. (If you don't specify null, you must
// specify an array of Type objects. For a parameterless property,
// use the built-in array with no elements: Type.EmptyTypes)
PropertyBuilder pbNumber = tb.DefineProperty(
"Number",
PropertyAttributes.HasDefault,
typeof(int),
null);
// The property "set" and property "get" methods require a special
// set of attributes.
MethodAttributes getSetAttr = MethodAttributes.Public |
MethodAttributes.SpecialName | MethodAttributes.HideBySig;
// Define the "get" accessor method for Number. The method returns
// an integer and has no arguments. (Note that null could be
// used instead of Types.EmptyTypes)
MethodBuilder mbNumberGetAccessor = tb.DefineMethod(
"get_Number",
getSetAttr,
typeof(int),
Type.EmptyTypes);
ILGenerator numberGetIL = mbNumberGetAccessor.GetILGenerator();
// For an instance property, argument zero is the instance. Load the
// instance, then load the private field and return, leaving the
// field value on the stack.
numberGetIL.Emit(OpCodes.Ldarg_0);
numberGetIL.Emit(OpCodes.Ldfld, fbNumber);
numberGetIL.Emit(OpCodes.Ret);
// Define the "set" accessor method for Number, which has no return
// type and takes one argument of type int (Int32).
MethodBuilder mbNumberSetAccessor = tb.DefineMethod(
"set_Number",
getSetAttr,
null,
new Type[] { typeof(int) });
ILGenerator numberSetIL = mbNumberSetAccessor.GetILGenerator();
// Load the instance and then the numeric argument, then store the
// argument in the field.
numberSetIL.Emit(OpCodes.Ldarg_0);
numberSetIL.Emit(OpCodes.Ldarg_1);
numberSetIL.Emit(OpCodes.Stfld, fbNumber);
numberSetIL.Emit(OpCodes.Ret);
// Last, map the "get" and "set" accessor methods to the
// PropertyBuilder. The property is now complete.
pbNumber.SetGetMethod(mbNumberGetAccessor);
pbNumber.SetSetMethod(mbNumberSetAccessor);
// Define a method that accepts an integer argument and returns
// the product of that integer and the private field m_number. This
// time, the array of parameter types is created on the fly.
MethodBuilder meth = tb.DefineMethod(
"MyMethod",
MethodAttributes.Public,
typeof(int),
new Type[] { typeof(int) });
ILGenerator methIL = meth.GetILGenerator();
// To retrieve the private instance field, load the instance it
// belongs to (argument zero). After loading the field, load the
// argument one and then multiply. Return from the method with
// the return value (the product of the two numbers) on the
// execution stack.
methIL.Emit(OpCodes.Ldarg_0);
methIL.Emit(OpCodes.Ldfld, fbNumber);
methIL.Emit(OpCodes.Ldarg_1);
methIL.Emit(OpCodes.Mul);
methIL.Emit(OpCodes.Ret);
// Finish the type.
Type? t = tb.CreateType();
// Because AssemblyBuilderAccess includes Run, the code can be
// executed immediately. Start by getting reflection objects for
// the method and the property.
MethodInfo? mi = t?.GetMethod("MyMethod");
PropertyInfo? pi = t?.GetProperty("Number");
// Create an instance of MyDynamicType using the default
// constructor.
object? o1 = null;
if (t is not null)
o1 = Activator.CreateInstance(t);
// Display the value of the property, then change it to 127 and
// display it again. Use null to indicate that the property
// has no index.
Console.WriteLine("o1.Number: {0}", pi?.GetValue(o1, null));
pi?.SetValue(o1, 127, null);
Console.WriteLine("o1.Number: {0}", pi?.GetValue(o1, null));
// Call MyMethod, passing 22, and display the return value, 22
// times 127. Arguments must be passed as an array, even when
// there is only one.
object[] arguments = { 22 };
Console.WriteLine("o1.MyMethod(22): {0}",
mi?.Invoke(o1, arguments));
// Create an instance of MyDynamicType using the constructor
// that specifies m_Number. The constructor is identified by
// matching the types in the argument array. In this case,
// the argument array is created on the fly. Display the
// property value.
object? o2 = null;
if (t is not null)
o2 = Activator.CreateInstance(t, new object[] { 5280 });
Console.WriteLine("o2.Number: {0}", pi?.GetValue(o2, null));
}
}
/* This code produces the following output:
o1.Number: 42
o1.Number: 127
o1.MyMethod(22): 2794
o2.Number: 5280
*/
open System
open System.Threading
open System.Reflection
open System.Reflection.Emit
// This code creates an assembly that contains one type,
// named "MyDynamicType", that has a private field, a property
// that gets and sets the private field, constructors that
// initialize the private field, and a method that multiplies
// a user-supplied number by the private field value and returns
// the result. In C# the type might look like this:
(*
public class MyDynamicType
{
private int m_number;
public MyDynamicType() : this(42) {}
public MyDynamicType(int initNumber)
{
m_number = initNumber;
}
public int Number
{
get { return m_number; }
set { m_number = value; }
}
public int MyMethod(int multiplier)
{
return m_number * multiplier;
}
}
*)
let assemblyName = new AssemblyName("DynamicAssemblyExample")
let assemblyBuilder =
AssemblyBuilder.DefineDynamicAssembly(
assemblyName,
AssemblyBuilderAccess.Run)
// The module name is usually the same as the assembly name.
let moduleBuilder =
assemblyBuilder.DefineDynamicModule(assemblyName.Name)
let typeBuilder =
moduleBuilder.DefineType(
"MyDynamicType",
TypeAttributes.Public)
// Add a private field of type int (Int32)
let fieldBuilderNumber =
typeBuilder.DefineField(
"m_number",
typeof<int>,
FieldAttributes.Private)
// Define a constructor1 that takes an integer argument and
// stores it in the private field.
let parameterTypes = [| typeof<int> |]
let ctor1 =
typeBuilder.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
parameterTypes)
let ctor1IL = ctor1.GetILGenerator()
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before calling the base
// class constructor. Specify the default constructor of the
// base class (System.Object) by passing an empty array of
// types (Type.EmptyTypes) to GetConstructor.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Call,
typeof<obj>.GetConstructor(Type.EmptyTypes))
// Push the instance on the stack before pushing the argument
// that is to be assigned to the private field m_number.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Ldarg_1)
ctor1IL.Emit(OpCodes.Stfld, fieldBuilderNumber)
ctor1IL.Emit(OpCodes.Ret)
// Define a default constructor1 that supplies a default value
// for the private field. For parameter types, pass the empty
// array of types or pass null.
let ctor0 =
typeBuilder.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
Type.EmptyTypes)
let ctor0IL = ctor0.GetILGenerator()
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before pushing the default
// value on the stack, then call constructor ctor1.
ctor0IL.Emit(OpCodes.Ldarg_0)
ctor0IL.Emit(OpCodes.Ldc_I4_S, 42)
ctor0IL.Emit(OpCodes.Call, ctor1)
ctor0IL.Emit(OpCodes.Ret)
// Define a property named Number that gets and sets the private
// field.
//
// The last argument of DefineProperty is null, because the
// property has no parameters. (If you don't specify null, you must
// specify an array of Type objects. For a parameterless property,
// use the built-in array with no elements: Type.EmptyTypes)
let propertyBuilderNumber =
typeBuilder.DefineProperty(
"Number",
PropertyAttributes.HasDefault,
typeof<int>,
null)
// The property "set" and property "get" methods require a special
// set of attributes.
let getSetAttr = MethodAttributes.Public ||| MethodAttributes.SpecialName ||| MethodAttributes.HideBySig
// Define the "get" accessor method for Number. The method returns
// an integer and has no arguments. (Note that null could be
// used instead of Types.EmptyTypes)
let methodBuilderNumberGetAccessor =
typeBuilder.DefineMethod(
"get_number",
getSetAttr,
typeof<int>,
Type.EmptyTypes)
let numberGetIL =
methodBuilderNumberGetAccessor.GetILGenerator()
// For an instance property, argument zero ir the instance. Load the
// instance, then load the private field and return, leaving the
// field value on the stack.
numberGetIL.Emit(OpCodes.Ldarg_0)
numberGetIL.Emit(OpCodes.Ldfld, fieldBuilderNumber)
numberGetIL.Emit(OpCodes.Ret)
// Define the "set" accessor method for Number, which has no return
// type and takes one argument of type int (Int32).
let methodBuilderNumberSetAccessor =
typeBuilder.DefineMethod(
"set_number",
getSetAttr,
null,
[| typeof<int> |])
let numberSetIL =
methodBuilderNumberSetAccessor.GetILGenerator()
// Load the instance and then the numeric argument, then store the
// argument in the field
numberSetIL.Emit(OpCodes.Ldarg_0)
numberSetIL.Emit(OpCodes.Ldarg_1)
numberSetIL.Emit(OpCodes.Stfld, fieldBuilderNumber)
numberSetIL.Emit(OpCodes.Ret)
// Last, map the "get" and "set" accessor methods to the
// PropertyBuilder. The property is now complete.
propertyBuilderNumber.SetGetMethod(methodBuilderNumberGetAccessor)
propertyBuilderNumber.SetSetMethod(methodBuilderNumberSetAccessor)
// Define a method that accepts an integer argument and returns
// the product of that integer and the private field m_number. This
// time, the array of parameter types is created on the fly.
let methodBuilder =
typeBuilder.DefineMethod(
"MyMethod",
MethodAttributes.Public,
typeof<int>,
[| typeof<int> |])
let methodIL = methodBuilder.GetILGenerator()
// To retrieve the private instance field, load the instance it
// belongs to (argument zero). After loading the field, load the
// argument one and then multiply. Return from the method with
// the return value (the product of the two numbers) on the
// execution stack.
methodIL.Emit(OpCodes.Ldarg_0)
methodIL.Emit(OpCodes.Ldfld, fieldBuilderNumber)
methodIL.Emit(OpCodes.Ldarg_1)
methodIL.Emit(OpCodes.Mul)
methodIL.Emit(OpCodes.Ret)
// Finish the type
let typ = typeBuilder.CreateType()
// Because AssemblyBuilderAccess includes Run, the code can be
// executed immediately. Start by getting reflection objects for
// the method and the property.
let methodInfo = typ.GetMethod("MyMethod")
let propertyInfo = typ.GetProperty("Number")
// Create an instance of MyDynamicType using the default
// constructor.
let obj1 = Activator.CreateInstance(typ)
// Display the value of the property, then change it to 127 and
// display it again. Use null to indicate that the property
// has no index.
printfn "obj1.Number: %A" (propertyInfo.GetValue(obj1, null))
propertyInfo.SetValue(obj1, 127, null)
printfn "obj1.Number: %A" (propertyInfo.GetValue(obj1, null))
// Call MyMethod, pasing 22, and display the return value, 22
// times 127. Arguments must be passed as an array, even when
// there is only one.
let arguments: obj array = [| 22 |]
printfn "obj1.MyMethod(22): %A" (methodInfo.Invoke(obj1, arguments))
// Create an instance of MyDynamicType using the constructor
// that specifies m_Number. The constructor is identified by
// matching the types in the argument array. In this case,
// the argument array is created on the fly. Display the
// property value.
let constructorArguments: obj array = [| 5280 |]
let obj2 = Activator.CreateInstance(typ, constructorArguments)
printfn "obj2.Number: %A" (propertyInfo.GetValue(obj2, null))
(* This code produces the following output:
obj1.Number: 42
obj1.Number: 127
obj1.MyMethod(22): 2794
obj1.Number: 5280
*)
Imports System.Reflection
Imports System.Reflection.Emit
Class DemoAssemblyBuilder
Public Shared Sub Main()
' This code creates an assembly that contains one type,
' named "MyDynamicType", that has a private field, a property
' that gets and sets the private field, constructors that
' initialize the private field, and a method that multiplies
' a user-supplied number by the private field value and returns
' the result. The code might look like this in Visual Basic:
'
'Public Class MyDynamicType
' Private m_number As Integer
'
' Public Sub New()
' Me.New(42)
' End Sub
'
' Public Sub New(ByVal initNumber As Integer)
' m_number = initNumber
' End Sub
'
' Public Property Number As Integer
' Get
' Return m_number
' End Get
' Set
' m_Number = Value
' End Set
' End Property
'
' Public Function MyMethod(ByVal multiplier As Integer) As Integer
' Return m_Number * multiplier
' End Function
'End Class
Dim aName As New AssemblyName("DynamicAssemblyExample")
Dim ab As AssemblyBuilder = _
AssemblyBuilder.DefineDynamicAssembly( _
aName, _
AssemblyBuilderAccess.Run)
' The module name is usually the same as the assembly name.
Dim mb As ModuleBuilder = ab.DefineDynamicModule( _
aName.Name)
Dim tb As TypeBuilder = _
mb.DefineType("MyDynamicType", TypeAttributes.Public)
' Add a private field of type Integer (Int32).
Dim fbNumber As FieldBuilder = tb.DefineField( _
"m_number", _
GetType(Integer), _
FieldAttributes.Private)
' Define a constructor that takes an integer argument and
' stores it in the private field.
Dim parameterTypes() As Type = { GetType(Integer) }
Dim ctor1 As ConstructorBuilder = _
tb.DefineConstructor( _
MethodAttributes.Public, _
CallingConventions.Standard, _
parameterTypes)
Dim ctor1IL As ILGenerator = ctor1.GetILGenerator()
' For a constructor, argument zero is a reference to the new
' instance. Push it on the stack before calling the base
' class constructor. Specify the default constructor of the
' base class (System.Object) by passing an empty array of
' types (Type.EmptyTypes) to GetConstructor.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Call, _
GetType(Object).GetConstructor(Type.EmptyTypes))
' Push the instance on the stack before pushing the argument
' that is to be assigned to the private field m_number.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Ldarg_1)
ctor1IL.Emit(OpCodes.Stfld, fbNumber)
ctor1IL.Emit(OpCodes.Ret)
' Define a default constructor that supplies a default value
' for the private field. For parameter types, pass the empty
' array of types or pass Nothing.
Dim ctor0 As ConstructorBuilder = tb.DefineConstructor( _
MethodAttributes.Public, _
CallingConventions.Standard, _
Type.EmptyTypes)
Dim ctor0IL As ILGenerator = ctor0.GetILGenerator()
' For a constructor, argument zero is a reference to the new
' instance. Push it on the stack before pushing the default
' value on the stack, then call constructor ctor1.
ctor0IL.Emit(OpCodes.Ldarg_0)
ctor0IL.Emit(OpCodes.Ldc_I4_S, 42)
ctor0IL.Emit(OpCodes.Call, ctor1)
ctor0IL.Emit(OpCodes.Ret)
' Define a property named Number that gets and sets the private
' field.
'
' The last argument of DefineProperty is Nothing, because the
' property has no parameters. (If you don't specify Nothing, you must
' specify an array of Type objects. For a parameterless property,
' use the built-in array with no elements: Type.EmptyTypes)
Dim pbNumber As PropertyBuilder = tb.DefineProperty( _
"Number", _
PropertyAttributes.HasDefault, _
GetType(Integer), _
Nothing)
' The property Set and property Get methods require a special
' set of attributes.
Dim getSetAttr As MethodAttributes = _
MethodAttributes.Public Or MethodAttributes.SpecialName _
Or MethodAttributes.HideBySig
' Define the "get" accessor method for Number. The method returns
' an integer and has no arguments. (Note that Nothing could be
' used instead of Types.EmptyTypes)
Dim mbNumberGetAccessor As MethodBuilder = tb.DefineMethod( _
"get_Number", _
getSetAttr, _
GetType(Integer), _
Type.EmptyTypes)
Dim numberGetIL As ILGenerator = mbNumberGetAccessor.GetILGenerator()
' For an instance property, argument zero is the instance. Load the
' instance, then load the private field and return, leaving the
' field value on the stack.
numberGetIL.Emit(OpCodes.Ldarg_0)
numberGetIL.Emit(OpCodes.Ldfld, fbNumber)
numberGetIL.Emit(OpCodes.Ret)
' Define the "set" accessor method for Number, which has no return
' type and takes one argument of type Integer (Int32).
Dim mbNumberSetAccessor As MethodBuilder = _
tb.DefineMethod( _
"set_Number", _
getSetAttr, _
Nothing, _
New Type() { GetType(Integer) })
Dim numberSetIL As ILGenerator = mbNumberSetAccessor.GetILGenerator()
' Load the instance and then the numeric argument, then store the
' argument in the field.
numberSetIL.Emit(OpCodes.Ldarg_0)
numberSetIL.Emit(OpCodes.Ldarg_1)
numberSetIL.Emit(OpCodes.Stfld, fbNumber)
numberSetIL.Emit(OpCodes.Ret)
' Last, map the "get" and "set" accessor methods to the
' PropertyBuilder. The property is now complete.
pbNumber.SetGetMethod(mbNumberGetAccessor)
pbNumber.SetSetMethod(mbNumberSetAccessor)
' Define a method that accepts an integer argument and returns
' the product of that integer and the private field m_number. This
' time, the array of parameter types is created on the fly.
Dim meth As MethodBuilder = tb.DefineMethod( _
"MyMethod", _
MethodAttributes.Public, _
GetType(Integer), _
New Type() { GetType(Integer) })
Dim methIL As ILGenerator = meth.GetILGenerator()
' To retrieve the private instance field, load the instance it
' belongs to (argument zero). After loading the field, load the
' argument one and then multiply. Return from the method with
' the return value (the product of the two numbers) on the
' execution stack.
methIL.Emit(OpCodes.Ldarg_0)
methIL.Emit(OpCodes.Ldfld, fbNumber)
methIL.Emit(OpCodes.Ldarg_1)
methIL.Emit(OpCodes.Mul)
methIL.Emit(OpCodes.Ret)
' Finish the type.
Dim t As Type = tb.CreateType()
' Because AssemblyBuilderAccess includes Run, the code can be
' executed immediately. Start by getting reflection objects for
' the method and the property.
Dim mi As MethodInfo = t.GetMethod("MyMethod")
Dim pi As PropertyInfo = t.GetProperty("Number")
' Create an instance of MyDynamicType using the default
' constructor.
Dim o1 As Object = Activator.CreateInstance(t)
' Display the value of the property, then change it to 127 and
' display it again. Use Nothing to indicate that the property
' has no index.
Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, Nothing))
pi.SetValue(o1, 127, Nothing)
Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, Nothing))
' Call MyMethod, passing 22, and display the return value, 22
' times 127. Arguments must be passed as an array, even when
' there is only one.
Dim arguments() As Object = { 22 }
Console.WriteLine("o1.MyMethod(22): {0}", _
mi.Invoke(o1, arguments))
' Create an instance of MyDynamicType using the constructor
' that specifies m_Number. The constructor is identified by
' matching the types in the argument array. In this case,
' the argument array is created on the fly. Display the
' property value.
Dim o2 As Object = Activator.CreateInstance(t, _
New Object() { 5280 })
Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, Nothing))
End Sub
End Class
' This code produces the following output:
'
'o1.Number: 42
'o1.Number: 127
'o1.MyMethod(22): 2794
'o2.Number: 5280
Remarks
For more information about this API, see Supplemental API remarks for AssemblyBuilder.
Constructors
AssemblyBuilder() |
Initializes a new instance of the AssemblyBuilder class. |
Properties
CodeBase |
Obsolete.
Gets the location of the assembly, as specified originally (such as in an AssemblyName object). |
CodeBase |
Obsolete.
Obsolete.
Gets the location of the assembly as specified originally, for example, in an AssemblyName object. (Inherited from Assembly) |
CustomAttributes |
Gets a collection that contains this assembly's custom attributes. (Inherited from Assembly) |
DefinedTypes | |
DefinedTypes |
Gets a collection of the types defined in this assembly. (Inherited from Assembly) |
EntryPoint |
Returns the entry point of this assembly. |
EntryPoint |
Gets the entry point of this assembly. (Inherited from Assembly) |
EscapedCodeBase |
Obsolete.
Obsolete.
Gets the URI, including escape characters, that represents the codebase. (Inherited from Assembly) |
Evidence |
Gets the evidence for this assembly. |
Evidence |
Gets the evidence for this assembly. (Inherited from Assembly) |
ExportedTypes |
Gets a collection of the public types defined in this assembly that are visible outside the assembly. (Inherited from Assembly) |
FullName |
Gets the display name of the current dynamic assembly. |
FullName |
Gets the display name of the assembly. (Inherited from Assembly) |
GlobalAssemblyCache |
Obsolete.
Gets a value that indicates whether the assembly was loaded from the global assembly cache. |
GlobalAssemblyCache |
Obsolete.
Gets a value indicating whether the assembly was loaded from the global assembly cache (.NET Framework only). (Inherited from Assembly) |
HostContext |
Gets the host context where the dynamic assembly is being created. |
HostContext |
Gets the host context with which the assembly was loaded. (Inherited from Assembly) |
ImageRuntimeVersion |
Gets the version of the common language runtime that will be saved in the file containing the manifest. |
ImageRuntimeVersion |
Gets a string representing the version of the common language runtime (CLR) saved in the file containing the manifest. (Inherited from Assembly) |
IsCollectible |
Gets a value that indicates whether this dynamic assembly is held in a collectible AssemblyLoadContext. |
IsCollectible |
Gets a value that indicates whether this assembly is held in a collectible AssemblyLoadContext. (Inherited from Assembly) |
IsDynamic |
Gets a value that indicates that the current assembly is a dynamic assembly. |
IsDynamic |
Gets a value that indicates whether the current assembly was generated dynamically in the current process by using reflection emit. (Inherited from Assembly) |
IsFullyTrusted |
Gets a value that indicates whether the current assembly is loaded with full trust. (Inherited from Assembly) |
Location |
Gets the location, in codebase format, of the loaded file that contains the manifest if it is not shadow-copied. |
Location |
Gets the full path or UNC location of the loaded file that contains the manifest. (Inherited from Assembly) |
ManifestModule |
Gets the module in the current AssemblyBuilder that contains the assembly manifest. |
ManifestModule |
Gets the module that contains the manifest for the current assembly. (Inherited from Assembly) |
Modules | |
Modules |
Gets a collection that contains the modules in this assembly. (Inherited from Assembly) |
PermissionSet |
Gets the grant set of the current dynamic assembly. |
PermissionSet |
Gets the grant set of the current assembly. (Inherited from Assembly) |
ReflectionOnly |
Gets a value indicating whether the dynamic assembly is in the reflection-only context. |
ReflectionOnly |
Gets a Boolean value indicating whether this assembly was loaded into the reflection-only context. (Inherited from Assembly) |
SecurityRuleSet |
Gets a value that indicates which set of security rules the common language runtime (CLR) enforces for this assembly. |
SecurityRuleSet |
Gets a value that indicates which set of security rules the common language runtime (CLR) enforces for this assembly. (Inherited from Assembly) |
Methods
AddResourceFile(String, String) |
Adds an existing resource file to this assembly. |
AddResourceFile(String, String, ResourceAttributes) |
Adds an existing resource file to this assembly. |
CreateInstance(String) |
Locates the specified type from this assembly and creates an instance of it using the system activator, using case-sensitive search. (Inherited from Assembly) |
CreateInstance(String, Boolean) |
Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search. (Inherited from Assembly) |
CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) |
Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search and having the specified culture, arguments, and binding and activation attributes. (Inherited from Assembly) |
DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess) |
Defines a dynamic assembly that has the specified name and access rights. |
DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>) |
Defines a new assembly that has the specified name, access rights, and attributes. |
DefineDynamicModule(String) |
Defines a named transient dynamic module in this assembly. |
DefineDynamicModule(String, Boolean) |
Defines a named transient dynamic module in this assembly and specifies whether symbol information should be emitted. |
DefineDynamicModule(String, String) |
Defines a persistable dynamic module with the given name that will be saved to the specified file. No symbol information is emitted. |
DefineDynamicModule(String, String, Boolean) |
Defines a persistable dynamic module, specifying the module name, the name of the file to which the module will be saved, and whether symbol information should be emitted using the default symbol writer. |
DefineDynamicModuleCore(String) |
When overridden in a derived class, defines a dynamic module in this assembly. |
DefineResource(String, String, String) |
Defines a standalone managed resource for this assembly with the default public resource attribute. |
DefineResource(String, String, String, ResourceAttributes) |
Defines a standalone managed resource for this assembly. Attributes can be specified for the managed resource. |
DefineUnmanagedResource(Byte[]) |
Defines an unmanaged resource for this assembly as an opaque blob of bytes. |
DefineUnmanagedResource(String) |
Defines an unmanaged resource file for this assembly given the name of the resource file. |
DefineVersionInfoResource() |
Defines an unmanaged version information resource using the information specified in the assembly's AssemblyName object and the assembly's custom attributes. |
DefineVersionInfoResource(String, String, String, String, String) |
Defines an unmanaged version information resource for this assembly with the given specifications. |
Equals(Object) |
Returns a value that indicates whether this instance is equal to the specified object. |
Equals(Object) |
Determines whether this assembly and the specified object are equal. (Inherited from Assembly) |
GetCustomAttributes(Boolean) |
Returns all the custom attributes that have been applied to the current AssemblyBuilder. |
GetCustomAttributes(Boolean) |
Gets all the custom attributes for this assembly. (Inherited from Assembly) |
GetCustomAttributes(Type, Boolean) |
Returns all the custom attributes that have been applied to the current AssemblyBuilder, and that derive from a specified attribute type. |
GetCustomAttributes(Type, Boolean) |
Gets the custom attributes for this assembly as specified by type. (Inherited from Assembly) |
GetCustomAttributesData() |
Returns CustomAttributeData objects that contain information about the attributes that have been applied to the current AssemblyBuilder. |
GetCustomAttributesData() |
Returns information about the attributes that have been applied to the current Assembly, expressed as CustomAttributeData objects. (Inherited from Assembly) |
GetDynamicModule(String) |
Returns the dynamic module with the specified name. |
GetDynamicModuleCore(String) |
When overridden in a derived class, returns the dynamic module with the specified name. |
GetExportedTypes() |
Gets the exported types defined in this assembly. |
GetExportedTypes() |
Gets the public types defined in this assembly that are visible outside the assembly. (Inherited from Assembly) |
GetFile(String) |
Gets a FileStream for the specified file in the file table of the manifest of this assembly. |
GetFile(String) |
Gets a FileStream for the specified file in the file table of the manifest of this assembly. (Inherited from Assembly) |
GetFiles() |
Gets the files in the file table of an assembly manifest. (Inherited from Assembly) |
GetFiles(Boolean) |
Gets the files in the file table of an assembly manifest, specifying whether to include resource modules. |
GetFiles(Boolean) |
Gets the files in the file table of an assembly manifest, specifying whether to include resource modules. (Inherited from Assembly) |
GetForwardedTypes() | (Inherited from Assembly) |
GetHashCode() |
Returns the hash code for this instance. |
GetHashCode() |
Returns the hash code for this instance. (Inherited from Assembly) |
GetLoadedModules() |
Gets all the loaded modules that are part of this assembly. (Inherited from Assembly) |
GetLoadedModules(Boolean) |
Returns all the loaded modules that are part of this assembly, and optionally includes resource modules. |
GetLoadedModules(Boolean) |
Gets all the loaded modules that are part of this assembly, specifying whether to include resource modules. (Inherited from Assembly) |
GetManifestResourceInfo(String) |
Returns information about how the given resource has been persisted. |
GetManifestResourceNames() |
Loads the specified manifest resource from this assembly. |
GetManifestResourceStream(String) |
Loads the specified manifest resource from this assembly. |
GetManifestResourceStream(Type, String) |
Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly. |
GetManifestResourceStream(Type, String) |
Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly. (Inherited from Assembly) |
GetModule(String) |
Gets the specified module in this assembly. |
GetModule(String) |
Gets the specified module in this assembly. (Inherited from Assembly) |
GetModules() |
Gets all the modules that are part of this assembly. (Inherited from Assembly) |
GetModules(Boolean) |
Gets all the modules that are part of this assembly, and optionally includes resource modules. |
GetModules(Boolean) |
Gets all the modules that are part of this assembly, specifying whether to include resource modules. (Inherited from Assembly) |
GetName() |
Gets an AssemblyName for this assembly. (Inherited from Assembly) |
GetName(Boolean) |
Gets the AssemblyName that was specified when the current dynamic assembly was created, and sets the code base as specified. |
GetName(Boolean) |
Gets an AssemblyName for this assembly, setting the codebase as specified by |
GetObjectData(SerializationInfo, StreamingContext) |
Obsolete.
Gets serialization information with all of the data needed to reinstantiate this assembly. (Inherited from Assembly) |
GetReferencedAssemblies() |
Gets an incomplete list of AssemblyName objects for the assemblies that are referenced by this AssemblyBuilder. |
GetReferencedAssemblies() |
Gets the AssemblyName objects for all the assemblies referenced by this assembly. (Inherited from Assembly) |
GetSatelliteAssembly(CultureInfo) |
Gets the satellite assembly for the specified culture. |
GetSatelliteAssembly(CultureInfo) |
Gets the satellite assembly for the specified culture. (Inherited from Assembly) |
GetSatelliteAssembly(CultureInfo, Version) |
Gets the specified version of the satellite assembly for the specified culture. |
GetSatelliteAssembly(CultureInfo, Version) |
Gets the specified version of the satellite assembly for the specified culture. (Inherited from Assembly) |
GetType() | (Inherited from Assembly) |
GetType(String) |
Gets the Type object with the specified name in the assembly instance. (Inherited from Assembly) |
GetType(String, Boolean) |
Gets the Type object with the specified name in the assembly instance and optionally throws an exception if the type is not found. (Inherited from Assembly) |
GetType(String, Boolean, Boolean) |
Gets the specified type from the types that have been defined and created in the current AssemblyBuilder. |
GetType(String, Boolean, Boolean) |
Gets the Type object with the specified name in the assembly instance, with the options of ignoring the case, and of throwing an exception if the type is not found. (Inherited from Assembly) |
GetTypes() |
Gets all types defined in this assembly. (Inherited from Assembly) |
IsDefined(Type, Boolean) |
Returns a value that indicates whether one or more instances of the specified attribute type is applied to this member. |
IsDefined(Type, Boolean) |
Indicates whether or not a specified attribute has been applied to the assembly. (Inherited from Assembly) |
LoadModule(String, Byte[]) |
Loads the module, internal to this assembly, with a common object file format (COFF)-based image containing an emitted module, or a resource file. (Inherited from Assembly) |
LoadModule(String, Byte[], Byte[]) |
Loads the module, internal to this assembly, with a common object file format (COFF)-based image containing an emitted module, or a resource file. The raw bytes representing the symbols for the module are also loaded. (Inherited from Assembly) |
MemberwiseClone() |
Creates a shallow copy of the current Object. (Inherited from Object) |
Save(String) |
Saves this dynamic assembly to disk. |
Save(String, PortableExecutableKinds, ImageFileMachine) |
Saves this dynamic assembly to disk, specifying the nature of code in the assembly's executables and the target platform. |
SetCustomAttribute(ConstructorInfo, Byte[]) |
Set a custom attribute on this assembly using a specified custom attribute blob. |
SetCustomAttribute(CustomAttributeBuilder) |
Set a custom attribute on this assembly using a custom attribute builder. |
SetCustomAttributeCore(ConstructorInfo, ReadOnlySpan<Byte>) |
When overridden in a derived class, sets a custom attribute on this assembly. |
SetEntryPoint(MethodInfo) |
Sets the entry point for this dynamic assembly, assuming that a console application is being built. |
SetEntryPoint(MethodInfo, PEFileKinds) |
Sets the entry point for this assembly and defines the type of the portable executable (PE file) being built. |
ToString() |
Returns the full name of the assembly, also known as the display name. (Inherited from Assembly) |
Events
ModuleResolve |
Occurs when the common language runtime class loader cannot resolve a reference to an internal module of an assembly through normal means. (Inherited from Assembly) |
Explicit Interface Implementations
_Assembly.GetType() |
Returns the type of the current instance. (Inherited from Assembly) |
_AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Maps a set of names to a corresponding set of dispatch identifiers. |
_AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr) |
Retrieves the type information for an object, which can then be used to get the type information for an interface. |
_AssemblyBuilder.GetTypeInfoCount(UInt32) |
Retrieves the number of type information interfaces that an object provides (either 0 or 1). |
_AssemblyBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Provides access to properties and methods exposed by an object. |
ICustomAttributeProvider.GetCustomAttributes(Boolean) |
Returns an array of all of the custom attributes defined on this member, excluding named attributes, or an empty array if there are no custom attributes. (Inherited from Assembly) |
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) |
Returns an array of custom attributes defined on this member, identified by type, or an empty array if there are no custom attributes of that type. (Inherited from Assembly) |
ICustomAttributeProvider.IsDefined(Type, Boolean) |
Indicates whether one or more instance of |
Extension Methods
GetExportedTypes(Assembly) | |
GetModules(Assembly) | |
GetTypes(Assembly) | |
GetCustomAttribute(Assembly, Type) |
Retrieves a custom attribute of a specified type that is applied to a specified assembly. |
GetCustomAttribute<T>(Assembly) |
Retrieves a custom attribute of a specified type that is applied to a specified assembly. |
GetCustomAttributes(Assembly) |
Retrieves a collection of custom attributes that are applied to a specified assembly. |
GetCustomAttributes(Assembly, Type) |
Retrieves a collection of custom attributes of a specified type that are applied to a specified assembly. |
GetCustomAttributes<T>(Assembly) |
Retrieves a collection of custom attributes of a specified type that are applied to a specified assembly. |
IsDefined(Assembly, Type) |
Indicates whether custom attributes of a specified type are applied to a specified assembly. |
TryGetRawMetadata(Assembly, Byte*, Int32) |
Retrieves the metadata section of the assembly, for use with MetadataReader. |
Applies to
See also
Pripomienky
https://aka.ms/ContentUserFeedback.
Pripravujeme: V priebehu roka 2024 postupne zrušíme službu Problémy v službe GitHub ako mechanizmus pripomienok týkajúcich sa obsahu a nahradíme ju novým systémom pripomienok. Ďalšie informácie nájdete na stránke:Odoslať a zobraziť pripomienky pre