AssemblyBuilder Clase

Definición

Define y representa un ensamblado dinámico.

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
Herencia
AssemblyBuilder
Atributos
Implementaciones

Ejemplos

En el ejemplo de código siguiente se muestra cómo definir y usar un ensamblado dinámico. El ensamblado de ejemplo contiene un tipo, MyDynamicType, que tiene un campo privado, una propiedad que obtiene y establece el campo privado, constructores que inicializan el campo privado y un método que multiplica un número proporcionado por el usuario por el valor del campo privado y devuelve el resultado.

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

Comentarios

Para obtener más información sobre esta API, consulte Comentarios complementarios de api para AssemblyBuilder.

Constructores

AssemblyBuilder()

Inicializa una nueva instancia de la clase AssemblyBuilder.

Propiedades

CodeBase
Obsoletos.

Obtiene la ubicación del ensamblado tal y como se especificó originalmente (como en un objeto AssemblyName).

CodeBase
Obsoletos.
Obsoletos.

Obtiene la ubicación del ensamblado tal como se especificó originalmente, por ejemplo, en un objeto AssemblyName.

(Heredado de Assembly)
CustomAttributes

Obtiene una colección que contiene los atributos personalizados de este ensamblado.

(Heredado de Assembly)
DefinedTypes

Define y representa un ensamblado dinámico.

DefinedTypes

Obtiene una colección de los tipos definidos en este ensamblado.

(Heredado de Assembly)
EntryPoint

Devuelve el punto de entrada de este ensamblado.

EntryPoint

Obtiene el punto de entrada de este ensamblado.

(Heredado de Assembly)
EscapedCodeBase
Obsoletos.
Obsoletos.

Obtiene el identificador URI, incluidos los caracteres de escape, que representa el código base.

(Heredado de Assembly)
Evidence

Obtiene la evidencia para este ensamblado.

Evidence

Obtiene la evidencia para este ensamblado.

(Heredado de Assembly)
ExportedTypes

Obtiene una colección de los tipos públicos definidos en este ensamblado que se pueden ver desde fuera del ensamblado.

(Heredado de Assembly)
FullName

Obtiene el nombre para mostrar del ensamblado dinámico actual.

FullName

Obtiene el nombre para mostrar del ensamblado.

(Heredado de Assembly)
GlobalAssemblyCache
Obsoletos.

Obtiene un valor que indica si el ensamblado se ha cargado desde la caché global de ensamblados.

GlobalAssemblyCache
Obsoletos.

Obtiene un valor que indica si el ensamblado se cargó desde la caché global de ensamblados (solo .NET Framework).

(Heredado de Assembly)
HostContext

Obtiene el contexto del host donde se está creando el ensamblado dinámico.

HostContext

Obtiene el contexto del host con el que se cargó el ensamblado.

(Heredado de Assembly)
ImageRuntimeVersion

Obtiene l versión de Common Language Runtime (CLR) que se guardará en el archivo que contiene el manifiesto.

ImageRuntimeVersion

Obtiene una cadena que representa la versión de Common Language Runtime (CLR) guardada en el archivo que contiene el manifiesto.

(Heredado de Assembly)
IsCollectible

Obtiene un valor que indica si este ensamblado dinámico se mantiene en un objeto recopilable AssemblyLoadContext.

IsCollectible

Obtiene un valor que indica si este ensamblado está contenido en un AssemblyLoadContext recopilable.

(Heredado de Assembly)
IsDynamic

Obtiene un valor que indica que el ensamblado actual es un ensamblado dinámico.

IsDynamic

Obtiene un valor que indica si el ensamblado actual se generó dinámicamente en el proceso actual utilizando emisión de la reflexión.

(Heredado de Assembly)
IsFullyTrusted

Obtiene un valor que indica si el ensamblado actual se carga con plena confianza.

(Heredado de Assembly)
Location

Obtiene la ubicación, en formato de código base, del archivo cargado que contiene el manifiesto si no se han creado instantáneas.

Location

Obtiene la ruta de acceso completa o la ubicación UNC del archivo cargado que contiene el manifiesto.

(Heredado de Assembly)
ManifestModule

Obtiene el módulo del AssemblyBuilder actual que contiene el manifiesto del ensamblado.

ManifestModule

Obtiene el módulo que contiene el manifiesto del ensamblado actual.

(Heredado de Assembly)
Modules

Define y representa un ensamblado dinámico.

Modules

Obtiene una colección que contiene los módulos de este ensamblado.

(Heredado de Assembly)
PermissionSet

Obtiene el conjunto de permisos del ensamblado dinámico actual.

PermissionSet

Obtiene el conjunto de permisos del ensamblado actual.

(Heredado de Assembly)
ReflectionOnly

Obtiene un valor que indica si el ensamblado dinámico está en el contexto de solo reflexión.

ReflectionOnly

Obtiene un valor Boolean que indica si este ensamblado se cargó en el contexto de solo reflexión.

(Heredado de Assembly)
SecurityRuleSet

Obtiene un valor que indica el conjunto de reglas de seguridad que Common Language Runtime (CLR) aplica para este ensamblado.

SecurityRuleSet

Obtiene un valor que indica el conjunto de reglas de seguridad que Common Language Runtime (CLR) aplica para este ensamblado.

(Heredado de Assembly)

Métodos

AddResourceFile(String, String)

Agrega un archivo de recursos existente a este ensamblado.

AddResourceFile(String, String, ResourceAttributes)

Agrega un archivo de recursos existente a este ensamblado.

CreateInstance(String)

Localiza el tipo especificado en este ensamblado y crea una instancia del tipo mediante el activador del sistema, realizando una búsqueda en la que se distingue entre mayúsculas y minúsculas.

(Heredado de Assembly)
CreateInstance(String, Boolean)

Ubica el tipo especificado de este ensamblado y crea una instancia de dicho tipo mediante el activador del sistema, con búsqueda de mayúsculas y minúsculas opcional.

(Heredado de Assembly)
CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

Ubica el tipo especificado en este ensamblado y crea una instancia de dicho tipo mediante el activador del sistema, con búsqueda de mayúsculas y minúsculas opcional y con los atributos de referencia cultural, argumentos, enlace y activación.

(Heredado de Assembly)
DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)

Define un ensamblado dinámico con el nombre y los derechos de acceso especificados.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)

Define un nuevo ensamblado con el nombre, los derechos de acceso y los atributos especificados.

DefineDynamicModule(String)

Define un módulo dinámico transitorio con nombre en este ensamblado.

DefineDynamicModule(String, Boolean)

Define un módulo dinámico transitorio con nombre en este ensamblado y especifica si se debe emitir información de símbolos.

DefineDynamicModule(String, String)

Define un módulo dinámico con persistencia con el nombre especificado que se guardará en el archivo especificado. No se emitirá información de símbolos.

DefineDynamicModule(String, String, Boolean)

Define un módulo dinámico con persistencia, especificando el nombre del módulo, el nombre del archivo en el que se guardará el módulo y si se debe emitir información de símbolos mediante el escritor de símbolos predeterminado.

DefineDynamicModuleCore(String)

Cuando se invalida en una clase derivada, define un módulo dinámico en este ensamblado.

DefinePersistedAssembly(AssemblyName, Assembly, IEnumerable<CustomAttributeBuilder>)

Define y representa un ensamblado dinámico.

DefineResource(String, String, String)

Define un recurso administrado independiente para este ensamblado con el atributo de recurso público predeterminado.

DefineResource(String, String, String, ResourceAttributes)

Define un recurso administrado independiente para este ensamblado. Los atributos se pueden especificar para el recurso administrado.

DefineUnmanagedResource(Byte[])

Define un recurso no administrado para este ensamblado como blob opaco de bytes.

DefineUnmanagedResource(String)

Define un archivo de recurso no administrado para este ensamblado con el nombre del archivo de recursos.

DefineVersionInfoResource()

Define un recurso de información de versión sin administrar mediante la información especificada en el objeto AssemblyName del ensamblado y los atributos personalizados del ensamblado.

DefineVersionInfoResource(String, String, String, String, String)

Define un recurso de información de versión no administrado para este ensamblado con las especificaciones dadas.

Equals(Object)

Devuelve un valor que indica si esta instancia es igual al objeto especificado.

Equals(Object)

Determina si este ensamblado y el objeto especificado son iguales.

(Heredado de Assembly)
GetCustomAttributes(Boolean)

Devuelve todos los atributos personalizados que se aplicaron al AssemblyBuilder actual.

GetCustomAttributes(Boolean)

Obtiene todos los atributos personalizados para este ensamblado.

(Heredado de Assembly)
GetCustomAttributes(Type, Boolean)

Devuelve todos los atributos personalizados que se aplicaron al AssemblyBuilder actual y que derivan de un tipo de atributo especificado.

GetCustomAttributes(Type, Boolean)

Obtiene los atributos personalizados para este ensamblado tal y como lo especifica el tipo.

(Heredado de Assembly)
GetCustomAttributesData()

Devuelve objetos CustomAttributeData que contienen información sobre los atributos que se aplicaron al AssemblyBuilder actual.

GetCustomAttributesData()

Devuelve información sobre los atributos que se han aplicado al Assembly actual, expresado como objetos CustomAttributeData.

(Heredado de Assembly)
GetDynamicModule(String)

Devuelve el módulo dinámico con el nombre especificado.

GetDynamicModuleCore(String)

Cuando se reemplaza en una clase derivada, devuelve el módulo dinámico con el nombre especificado.

GetExportedTypes()

Obtiene los tipos definidos en este ensamblado.

GetExportedTypes()

Obtiene los tipos públicos definidos en este ensamblado que se pueden ver desde fuera del ensamblado.

(Heredado de Assembly)
GetFile(String)

Obtiene un objeto FileStream para el archivo especificado en la tabla de archivos del manifiesto de este ensamblado.

GetFile(String)

Obtiene un objeto FileStream para el archivo especificado en la tabla de archivos del manifiesto de este ensamblado.

(Heredado de Assembly)
GetFiles()

Obtiene los archivos en la tabla de archivos del manifiesto del ensamblado.

(Heredado de Assembly)
GetFiles(Boolean)

Obtiene los archivos en la tabla de archivos del manifiesto del ensamblado, especificando si deben incluirse módulos de recursos.

GetFiles(Boolean)

Obtiene los archivos en la tabla de archivos del manifiesto del ensamblado, especificando si deben incluirse módulos de recursos.

(Heredado de Assembly)
GetForwardedTypes()

Define y representa un ensamblado dinámico.

(Heredado de Assembly)
GetHashCode()

Devuelve el código hash de esta instancia.

GetHashCode()

Devuelve el código hash de esta instancia.

(Heredado de Assembly)
GetLoadedModules()

Obtiene todos los módulos cargados que forman parte de este ensamblado.

(Heredado de Assembly)
GetLoadedModules(Boolean)

Devuelve todos los módulos cargados que forman parte de este ensamblado e incluye opcionalmente módulos de recursos.

GetLoadedModules(Boolean)

Obtiene todos los módulos cargados que forman parte de este ensamblado, especificando si se deben incluir módulos de recursos.

(Heredado de Assembly)
GetManifestResourceInfo(String)

Devuelve información sobre cómo el recurso dado ha persistido.

GetManifestResourceNames()

Carga el recurso del manifiesto especificado a partir de este ensamblado.

GetManifestResourceStream(String)

Carga el recurso del manifiesto especificado a partir de este ensamblado.

GetManifestResourceStream(Type, String)

Carga el recurso del manifiesto especificado según el espacio de nombres del tipo especificado a partir de este ensamblado.

GetManifestResourceStream(Type, String)

Carga el recurso del manifiesto especificado según el espacio de nombres del tipo especificado a partir de este ensamblado.

(Heredado de Assembly)
GetModule(String)

Obtiene el módulo especificado en este ensamblado.

GetModule(String)

Obtiene el módulo especificado en este ensamblado.

(Heredado de Assembly)
GetModules()

Obtiene todos los módulos que forman parte de este ensamblado.

(Heredado de Assembly)
GetModules(Boolean)

Obtiene todos los módulos que forman parte de este ensamblado e incluye opcionalmente módulos de recursos.

GetModules(Boolean)

Obtiene todos los módulos que forman parte de este ensamblado e indica si se deben incluir módulos de recursos.

(Heredado de Assembly)
GetName()

Obtiene un AssemblyName para este ensamblado.

(Heredado de Assembly)
GetName(Boolean)

Obtiene el AssemblyName que se especificó cuando se creó el ensamblado dinámico actual y establece el código base según lo especificado.

GetName(Boolean)

Obtiene un objeto AssemblyName para este ensamblado y establece el código base tal como especifica copiedName.

(Heredado de Assembly)
GetObjectData(SerializationInfo, StreamingContext)
Obsoletos.

Obtiene información de serialización con todos los datos necesarios para crear una nueva instancia de este ensamblado.

(Heredado de Assembly)
GetReferencedAssemblies()

Obtiene una lista incompleta de objetos AssemblyName para los ensamblados a los que hace referencia este AssemblyBuilder.

GetReferencedAssemblies()

Obtiene los objetos AssemblyName de todos los ensamblados a los que hace referencia este ensamblado.

(Heredado de Assembly)
GetSatelliteAssembly(CultureInfo)

Obtiene el ensamblado satélite para la referencia cultural especificada.

GetSatelliteAssembly(CultureInfo)

Obtiene el ensamblado satélite para la referencia cultural especificada.

(Heredado de Assembly)
GetSatelliteAssembly(CultureInfo, Version)

Obtiene la versión especificada del ensamblado satélite para la referencia cultural especificada.

GetSatelliteAssembly(CultureInfo, Version)

Obtiene la versión especificada del ensamblado satélite para la referencia cultural especificada.

(Heredado de Assembly)
GetType()

Define y representa un ensamblado dinámico.

(Heredado de Assembly)
GetType(String)

Obtiene el objeto Type con el nombre especificado en la instancia de ensamblado.

(Heredado de Assembly)
GetType(String, Boolean)

Obtiene el objeto Type con el nombre especificado en la instancia de ensamblado y, de manera opcional, produce una excepción si no se encuentra el tipo.

(Heredado de Assembly)
GetType(String, Boolean, Boolean)

Obtiene el tipo especificado a partir de los tipos que se definieron y se crearon en el AssemblyBuilder actual.

GetType(String, Boolean, Boolean)

Obtiene el objeto Type con el nombre especificado en la instancia de ensamblado, con la opción de omitir el caso y de producir una excepción si no se encuentra el tipo.

(Heredado de Assembly)
GetTypes()

Obtiene todos los tipos definidos en este ensamblado.

(Heredado de Assembly)
IsDefined(Type, Boolean)

Devuelve un valor que indica si se aplica a este miembro una o más instancias del tipo de atributo especificado.

IsDefined(Type, Boolean)

Indica si se ha aplicado un atributo especificado al ensamblado.

(Heredado de Assembly)
LoadModule(String, Byte[])

Carga el módulo, que es interno para este ensamblado, con una imagen que toma como base el formato Common Object File Format (COFF) y que contiene un módulo emitido o un archivo de recursos.

(Heredado de Assembly)
LoadModule(String, Byte[], Byte[])

Carga el módulo, que es interno para este ensamblado, con una imagen que toma como base el formato Common Object File Format (COFF) y que contiene un módulo emitido o un archivo de recursos. También se cargan los bytes sin formato que representan a los símbolos del módulo.

(Heredado de Assembly)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
Save(Stream)

Define y representa un ensamblado dinámico.

Save(String)

Guarda este ensamblado dinámico en el disco.

Save(String, PortableExecutableKinds, ImageFileMachine)

Guarda este ensamblado dinámico en el disco, especificando la naturaleza del código en los ejecutables del ensamblado y en la plataforma de destino.

SaveCore(Stream)

Define y representa un ensamblado dinámico.

SetCustomAttribute(ConstructorInfo, Byte[])

Establezca un atributo personalizado en este ensamblado mediante un blob de atributo personalizado especificado.

SetCustomAttribute(CustomAttributeBuilder)

Establezca un atributo personalizado en este ensamblado mediante un generador de atributos personalizado.

SetCustomAttributeCore(ConstructorInfo, ReadOnlySpan<Byte>)

Cuando se reemplaza en una clase derivada, establece un atributo personalizado en este ensamblado.

SetEntryPoint(MethodInfo)

Establece el punto de entrada para este ensamblado dinámico, suponiendo que se está generando una aplicación de consola.

SetEntryPoint(MethodInfo, PEFileKinds)

Establece el punto de entrada de este ensamblado y define el tipo de archivo ejecutable portátil (archivo PE) que se está generando.

ToString()

Devuelve el nombre completo del ensamblado, también conocido como nombre para mostrar.

(Heredado de Assembly)

Eventos

ModuleResolve

Se produce cuando el cargador de clases Common Language Runtime no puede resolver una referencia a un módulo interno de un ensamblado por medios normales.

(Heredado de Assembly)

Implementaciones de interfaz explícitas

_Assembly.GetType()

Devuelve el tipo de la instancia actual.

(Heredado de Assembly)
_AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.

_AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera la información de tipo de un objeto, que se puede usar después para obtener la información de tipo de una interfaz.

_AssemblyBuilder.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).

_AssemblyBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.

ICustomAttributeProvider.GetCustomAttributes(Boolean)

Devuelve una matriz de todos los atributos personalizados definidos en este miembro, excluidos los atributos con nombre, o una matriz vacía si no hay atributos personalizados.

(Heredado de Assembly)
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean)

Devuelve una matriz de atributos personalizados definidos en este miembro, identificados por tipo, o una matriz vacía si no hay atributos personalizados de ese tipo.

(Heredado de Assembly)
ICustomAttributeProvider.IsDefined(Type, Boolean)

Indica si una o más instancias de attributeType se definen en este miembro.

(Heredado de Assembly)

Métodos de extensión

GetExportedTypes(Assembly)

Define y representa un ensamblado dinámico.

GetModules(Assembly)

Define y representa un ensamblado dinámico.

GetTypes(Assembly)

Define y representa un ensamblado dinámico.

GetCustomAttribute(Assembly, Type)

Recupera un atributo personalizado de un tipo especificado que se aplica a un ensamblado concreto.

GetCustomAttribute<T>(Assembly)

Recupera un atributo personalizado de un tipo especificado que se aplica a un ensamblado concreto.

GetCustomAttributes(Assembly)

Recupera una colección de atributos personalizados que se aplican a un ensamblado especificado.

GetCustomAttributes(Assembly, Type)

Recupera una colección de atributos personalizados de un tipo especificado que se aplican a un ensamblado concreto.

GetCustomAttributes<T>(Assembly)

Recupera una colección de atributos personalizados de un tipo especificado que se aplican a un ensamblado concreto.

IsDefined(Assembly, Type)

Indica si se deben aplicar atributos personalizados de un tipo especificado a un ensamblado especificado.

TryGetRawMetadata(Assembly, Byte*, Int32)

Recupera la sección de metadatos del ensamblado para su uso con MetadataReader.

Se aplica a

Consulte también