AssemblyBuilder AssemblyBuilder AssemblyBuilder AssemblyBuilder Class

Definición

Define y representa un ensamblado dinámico.Defines and represents a dynamic assembly.

public ref class AssemblyBuilder sealed : 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
    interface _AssemblyBuilder
Public NotInheritable Class AssemblyBuilder
Inherits Assembly
Implements _AssemblyBuilder
Herencia
AssemblyBuilderAssemblyBuilderAssemblyBuilderAssemblyBuilder
Atributos
Implementaciones

Ejemplos

El ejemplo de código siguiente muestra cómo definir un ensamblado dinámico con un módulo.The following code example shows how to define a dynamic assembly with one module. El módulo en el ensamblado de ejemplo contiene un solo tipo, MyDynamicType, que tiene un campo privado, una propiedad que obtiene y establece el campo privado, los constructores que inicializan el campo privado y un método que multiplica un número proporcionado por el usuario mediante el campo privado valor y devuelve el resultado.The module in the example assembly contains one type, MyDynamicType, which 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.

AssemblyBuilderAccess.RunAndSave se especifica cuando se crea el ensamblado.AssemblyBuilderAccess.RunAndSave is specified when the assembly is created. El código de ensamblado se usa inmediatamente, y el ensamblado también se guarda en el disco para que éste puede examinarse con Ildasm.exe (Desensamblador de IL) o se usa en otro programa.The assembly code is used immediately, and the assembly is also saved to disk so that it can be examined with Ildasm.exe (IL Disassembler) or used in another program.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;

void main()
{
    // An assembly consists of one or more modules, each of which
    // contains zero or more types. This code creates a single-module
    // assembly, the most common case. The module 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 = 
        AppDomain::CurrentDomain->DefineDynamicAssembly(
            aName, 
            AssemblyBuilderAccess::RunAndSave);

    // For a single-module assembly, the module name is usually
    // the assembly name plus an extension.
    ModuleBuilder^ mb = 
        ab->DefineDynamicModule(aName->Name, aName->Name + ".dll");
      
    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();
     
    // The following line saves the single-module assembly. This
    // requires AssemblyBuilderAccess to include Save. You can now
    // type "ildasm MyDynamicAsm.dll" at the command prompt, and 
    // examine the assembly. You can also write a program that has
    // a reference to the assembly, and use the MyDynamicType type.
    // 
    ab->Save(aName->Name + ".dll");

    // 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()
    {
        // An assembly consists of one or more modules, each of which
        // contains zero or more types. This code creates a single-module
        // assembly, the most common case. The module 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;
            }
        }
        */
      
        AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
        AssemblyBuilder ab = 
            AppDomain.CurrentDomain.DefineDynamicAssembly(
                aName, 
                AssemblyBuilderAccess.RunAndSave);

        // For a single-module assembly, the module name is usually
        // the assembly name plus an extension.
        ModuleBuilder mb = 
            ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
      
        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);
        ctor1IL.Emit(OpCodes.Call, 
            typeof(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 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();
     
        // The following line saves the single-module assembly. This
        // requires AssemblyBuilderAccess to include Save. You can now
        // type "ildasm MyDynamicAsm.dll" at the command prompt, and 
        // examine the assembly. You can also write a program that has
        // a reference to the assembly, and use the MyDynamicType type.
        // 
        ab.Save(aName.Name + ".dll");

        // 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 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 = 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
 */
Imports System
Imports System.Reflection
Imports System.Reflection.Emit

Class DemoAssemblyBuilder

    Public Shared Sub Main()

        ' An assembly consists of one or more modules, each of which
        ' contains zero or more types. This code creates a single-module
        ' assembly, the most common case. The module 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 = _
            AppDomain.CurrentDomain.DefineDynamicAssembly( _
                aName, _
                AssemblyBuilderAccess.RunAndSave)

        ' For a single-module assembly, the module name is usually
        ' the assembly name plus an extension.
        Dim mb As ModuleBuilder = ab.DefineDynamicModule( _
            aName.Name, _
            aName.Name & ".dll")
      
        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()
     
        ' The following line saves the single-module assembly. This
        ' requires AssemblyBuilderAccess to include Save. You can now
        ' type "ildasm MyDynamicAsm.dll" at the command prompt, and 
        ' examine the assembly. You can also write a program that has
        ' a reference to the assembly, and use the MyDynamicType type.
        ' 
        ab.Save(aName.Name & ".dll") 

        ' 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

Un ensamblado dinámico es un ensamblado que se crea mediante las API de emisión de reflexión.A dynamic assembly is an assembly that is created using the Reflection Emit APIs. Los módulos dinámicos del ensamblado se guardan cuando se guarda el ensamblado dinámico mediante la Save método.The dynamic modules in the assembly are saved when the dynamic assembly is saved using the Save method. Para generar un archivo ejecutable, el SetEntryPoint método debe llamarse para identificar el método que es el punto de entrada para el ensamblado.To generate an executable, the SetEntryPoint method must be called to identify the method that is the entry point to the assembly. Los ensamblados se guardan como archivos DLL de forma predeterminada, a menos que el SetEntryPoint método solicita la generación de una aplicación de consola o una aplicación basada en Windows.Assemblies are saved as DLLs by default, unless the SetEntryPoint method requests the generation of a console application or a Windows-based application.

Si un ensamblado dinámico contiene más de un módulo dinámico, el nombre de archivo de manifiesto del ensamblado debe coincidir con el nombre del módulo que se especifica como el primer argumento para el DefineDynamicModule método.If a dynamic assembly contains more than one dynamic module, the assembly's manifest file name should match the module's name that is specified as the first argument to the DefineDynamicModule method.

Algunos métodos en la base de Assembly clase, como GetModules y GetLoadedModules, no funcionará correctamente cuando se llama desde AssemblyBuilder objetos.Some methods on the base Assembly class, such as GetModules and GetLoadedModules, will not work correctly when called from AssemblyBuilder objects. Puede cargar el ensamblado dinámico definido y llamar a los métodos en el ensamblado cargado.You can load the defined dynamic assembly and call the methods on the loaded assembly. Por ejemplo, para asegurarse de que los módulos de recursos se incluyen en la lista de módulos devuelta, llame a GetModules en cargado Assembly objeto.For example, to ensure that resource modules are included in the returned module list, call GetModules on the loaded Assembly object.

La firma de un ensamblado dinámico usando KeyPair no es efectivo hasta que el ensamblado se guarda en el disco.The signing of a dynamic assembly using KeyPair is not effective until the assembly is saved to disk. Por lo tanto, los nombres seguros no funcionará con los ensamblados dinámicos transitorios.So, strong names will not work with transient dynamic assemblies.

Para obtener un AssemblyBuilder de objeto, utilice el AppDomain.DefineDynamicAssembly método.To get an AssemblyBuilder object, use the AppDomain.DefineDynamicAssembly method.

Escenarios de ensamblado dinámico de emisión de reflexiónReflection emit dynamic assembly scenarios

Los siguientes son algunas cosas a tener en cuenta cuando se usa el AssemblyBuilder clase para crear ensamblados dinámicos.The following are some things to consider when using the AssemblyBuilder class to create dynamic assemblies.

Módulos dinámicosDynamic modules

Emisión de reflexión admite la creación de módulos dinámicos definidos en ensamblados dinámicos.Reflection emit supports the creation of dynamic modules defined in dynamic assemblies. Puede ser un módulo dinámico creado en un ensamblado dinámico transitorio o persistente.A dynamic module created in a dynamic assembly can be transient or persistable.

Restricciones en las referencias de tiposRestrictions on type references

Los ensamblados pueden hacer referencia a tipos definidos en otro ensamblado.Assemblies can reference types defined in another assembly. Un ensamblado dinámico transitorio con seguridad puede hacer referencia a tipos definidos en otro ensamblado dinámico transitorio, un ensamblado dinámico con persistencia o un ensamblado estático.A transient dynamic assembly can safely reference types defined in another transient dynamic assembly, a persistable dynamic assembly, or a static assembly. Sin embargo, common language runtime no permite un módulo dinámico con persistencia hacer referencia a un tipo definido en un módulo dinámico transitorio.However, the common language runtime does not allow a persistable dynamic module to reference a type defined in a transient dynamic module. Esto es porque cuando se carga el módulo dinámico con persistencia después de guardarlas en el disco, el tiempo de ejecución no puede resolver las referencias a tipos definidos en el módulo dinámico transitorio.This is because when the persisted dynamic module is loaded after being saved to disk, the runtime cannot resolve the references to types defined in the transient dynamic module.

Restricciones en la emisión a dominios de aplicación remotaRestrictions on emitting to remote application domains

Algunos escenarios requieren un ensamblado dinámico se creen y se ejecuta en un dominio de aplicación remota.Some scenarios require a dynamic assembly to be created and executed in a remote application domain. Emisión de reflexión no permite un ensamblado dinámico que se emitan directamente a un dominio de aplicación remota.Reflection emit does not allow a dynamic assembly to be emitted directly to a remote application domain. La solución consiste en emitir el ensamblado dinámico en el dominio de aplicación actual, guardar el ensamblado dinámico emitido en el disco y, a continuación, cargar el ensamblado dinámico en el dominio de aplicación remota.The solution is to emit the dynamic assembly in the current application domain, save the emitted dynamic assembly to disk, and then load the dynamic assembly into the remote application domain.

Modos de acceso del ensamblado dinámicoDynamic assembly access modes

Ensamblados dinámicos se pueden crear mediante uno de los siguientes modos de acceso:Dynamic assemblies can be created using one of the following access modes:

  • AssemblyBuilderAccess.Run

    El ensamblado dinámico representado por un AssemblyBuilder objeto es transitorio.The dynamic assembly represented by an AssemblyBuilder object is transient. El ensamblado dinámico solo puede utilizarse para ejecutar el código emitido.The dynamic assembly can only be used to execute the emitted code.

  • AssemblyBuilderAccess.Save

    El ensamblado dinámico representado por un AssemblyBuilder objeto puede persistir, pero no se puede ejecutar hasta que se ha cargado el archivo guardado portable ejecutable (PE) desde el disco.The dynamic assembly represented by an AssemblyBuilder object is persistable but cannot be executed until the saved portable executable (PE) file has been loaded from disk.

  • AssemblyBuilderAccess.RunAndSave

    El ensamblado dinámico representado por un AssemblyBuilder objeto puede persistir, pero también se puede ejecutar antes o después de guarda el ensamblado en el disco.The dynamic assembly represented by an AssemblyBuilder object is persistable, but can also be executed before and/or after the assembly is saved to disk.

Se debe especificar el modo de acceso proporcionando adecuado AssemblyBuilderAccess valor en la llamada a la AssemblyBuilder.DefineDynamicAssembly método cuando el ensamblado dinámico está definido y no se puede cambiar más adelante.The access mode must be specified by providing the appropriate AssemblyBuilderAccess value in the call to the AssemblyBuilder.DefineDynamicAssembly method when the dynamic assembly is defined and cannot be changed later. El runtime usa el modo de acceso de un ensamblado dinámico para optimizar la representación interna del ensamblado.The runtime uses the access mode of a dynamic assembly to optimize the assembly's internal representation.

Constructores

AssemblyBuilder() AssemblyBuilder() AssemblyBuilder() AssemblyBuilder()

Propiedades

CodeBase CodeBase CodeBase CodeBase

Obtiene la ubicación del ensamblado tal y como se especificó originalmente (como en un objeto AssemblyName).Gets the location of the assembly, as specified originally (such as in an AssemblyName object).

CustomAttributes CustomAttributes CustomAttributes CustomAttributes

Obtiene una colección que contiene los atributos personalizados de este ensamblado.Gets a collection that contains this assembly's custom attributes.

(Inherited from Assembly)
DefinedTypes DefinedTypes DefinedTypes DefinedTypes
EntryPoint EntryPoint EntryPoint EntryPoint

Devuelve el punto de entrada de este ensamblado.Returns the entry point of this assembly.

EscapedCodeBase EscapedCodeBase EscapedCodeBase EscapedCodeBase

Obtiene el identificador URI, incluidos los caracteres de escape, que representa el código base.Gets the URI, including escape characters, that represents the codebase.

(Inherited from Assembly)
Evidence Evidence Evidence Evidence

Obtiene la evidencia para este ensamblado.Gets the evidence for this assembly.

ExportedTypes ExportedTypes ExportedTypes ExportedTypes

Obtiene una colección de los tipos públicos definidos en este ensamblado que se pueden ver desde fuera del ensamblado.Gets a collection of the public types defined in this assembly that are visible outside the assembly.

(Inherited from Assembly)
FullName FullName FullName FullName

Obtiene el nombre para mostrar del ensamblado dinámico actual.Gets the display name of the current dynamic assembly.

GlobalAssemblyCache GlobalAssemblyCache GlobalAssemblyCache GlobalAssemblyCache

Obtiene un valor que indica si el ensamblado se ha cargado desde la memoria caché global de ensamblados.Gets a value that indicates whether the assembly was loaded from the global assembly cache.

HostContext HostContext HostContext HostContext

Obtiene el contexto del host donde se está creando el ensamblado dinámico.Gets the host context where the dynamic assembly is being created.

ImageRuntimeVersion ImageRuntimeVersion ImageRuntimeVersion ImageRuntimeVersion

Obtiene la versión de Common Language Runtime que se guardará en el archivo que contiene el manifiesto.Gets the version of the common language runtime that will be saved in the file containing the manifest.

IsCollectible IsCollectible IsCollectible IsCollectible

Obtiene un valor que indica si este ensamblado está contenido en un AssemblyLoadContext recopilable.Gets a value that indicates whether this assembly is held in a collectible AssemblyLoadContext.

(Inherited from Assembly)
IsDynamic IsDynamic IsDynamic IsDynamic

Obtiene un valor que indica que el ensamblado actual es un ensamblado dinámico.Gets a value that indicates that the current assembly is a dynamic assembly.

IsFullyTrusted IsFullyTrusted IsFullyTrusted IsFullyTrusted

Obtiene un valor que indica si el ensamblado actual se carga con plena confianza.Gets a value that indicates whether the current assembly is loaded with full trust.

(Inherited from Assembly)
Location Location Location Location

Obtiene la ubicación, en formato de código base, del archivo cargado que contiene el manifiesto si no se ha realizado copia de seguridad.Gets the location, in codebase format, of the loaded file that contains the manifest if it is not shadow-copied.

ManifestModule ManifestModule ManifestModule ManifestModule

Obtiene el módulo de la clase AssemblyBuilder actual que contiene el manifiesto del ensamblado.Gets the module in the current AssemblyBuilder that contains the assembly manifest.

Modules Modules Modules Modules
PermissionSet PermissionSet PermissionSet PermissionSet

Obtiene el conjunto de permisos del ensamblado dinámico actual.Gets the grant set of the current dynamic assembly.

ReflectionOnly ReflectionOnly ReflectionOnly ReflectionOnly

Obtiene un valor que indica si el ensamblado dinámico está en el contexto de sólo reflexión.Gets a value indicating whether the dynamic assembly is in the reflection-only context.

SecurityRuleSet SecurityRuleSet SecurityRuleSet SecurityRuleSet

Obtiene un valor que indica el conjunto de reglas de seguridad que Common Language Runtime (CLR) aplica para este ensamblado.Gets a value that indicates which set of security rules the common language runtime (CLR) enforces for this assembly.

Métodos

AddResourceFile(String, String) AddResourceFile(String, String) AddResourceFile(String, String) AddResourceFile(String, String)

Agrega un archivo de recursos existente a este ensamblado.Adds an existing resource file to this assembly.

AddResourceFile(String, String, ResourceAttributes) AddResourceFile(String, String, ResourceAttributes) AddResourceFile(String, String, ResourceAttributes) AddResourceFile(String, String, ResourceAttributes)

Agrega un archivo de recursos existente a este ensamblado.Adds an existing resource file to this assembly.

CreateInstance(String) CreateInstance(String) CreateInstance(String) 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.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) CreateInstance(String, Boolean) CreateInstance(String, Boolean) 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.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[]) CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) 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.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) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)

Define un ensamblado dinámico que tiene los derechos de acceso y nombre especificados.Defines a dynamic assembly that has the specified name and access rights.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)

Define un nuevo ensamblado que tiene el nombre, los derechos de acceso y los atributos especificados.Defines a new assembly that has the specified name, access rights, and attributes.

DefineDynamicModule(String) DefineDynamicModule(String) DefineDynamicModule(String) DefineDynamicModule(String)

Define un módulo dinámico transitorio con nombre en este ensamblado.Defines a named transient dynamic module in this assembly.

DefineDynamicModule(String, Boolean) DefineDynamicModule(String, Boolean) DefineDynamicModule(String, Boolean) DefineDynamicModule(String, Boolean)

Define un módulo dinámico transitorio con nombre en este ensamblado y especifica si debe emitirse información de símbolos.Defines a named transient dynamic module in this assembly and specifies whether symbol information should be emitted.

DefineDynamicModule(String, String) DefineDynamicModule(String, String) DefineDynamicModule(String, String) DefineDynamicModule(String, String)

Define un módulo dinámico con persistencia con el nombre especificado que se guardará en el archivo indicado.Defines a persistable dynamic module with the given name that will be saved to the specified file. No se emite información de símbolos.No symbol information is emitted.

DefineDynamicModule(String, String, Boolean) DefineDynamicModule(String, String, Boolean) DefineDynamicModule(String, String, Boolean) 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 va a guardar el módulo y si se debe emitir información de símbolos mediante el sistema de escritura de símbolos predeterminado.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.

DefineResource(String, String, String) DefineResource(String, String, String) DefineResource(String, String, String) DefineResource(String, String, String)

Define un recurso administrado independiente para este ensamblado con el atributo de recurso público predeterminado.Defines a standalone managed resource for this assembly with the default public resource attribute.

DefineResource(String, String, String, ResourceAttributes) DefineResource(String, String, String, ResourceAttributes) DefineResource(String, String, String, ResourceAttributes) DefineResource(String, String, String, ResourceAttributes)

Define un recurso administrado independiente para este ensamblado.Defines a standalone managed resource for this assembly. Se pueden especificar atributos para el recurso administrado.Attributes can be specified for the managed resource.

DefineUnmanagedResource(Byte[]) DefineUnmanagedResource(Byte[]) DefineUnmanagedResource(Byte[]) DefineUnmanagedResource(Byte[])

Define un recurso no administrado para este ensamblado como un objeto binario opaco de bytes.Defines an unmanaged resource for this assembly as an opaque blob of bytes.

DefineUnmanagedResource(String) DefineUnmanagedResource(String) DefineUnmanagedResource(String) DefineUnmanagedResource(String)

Define un archivo de recursos no administrados para este ensamblado a partir del nombre del archivo de recursos.Defines an unmanaged resource file for this assembly given the name of the resource file.

DefineVersionInfoResource() DefineVersionInfoResource() DefineVersionInfoResource() DefineVersionInfoResource()

Define un recurso de información de versión no administrado con la información especificada en el objeto AssemblyName del ensamblado y los atributos personalizados del mismo.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) DefineVersionInfoResource(String, String, String, String, String) DefineVersionInfoResource(String, String, String, String, String) DefineVersionInfoResource(String, String, String, String, String)

Define un recurso de información de versión no administrado para este ensamblado con las especificaciones dadas.Defines an unmanaged version information resource for this assembly with the given specifications.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Devuelve un valor que indica si esta instancia es igual que el objeto especificado.Returns a value that indicates whether this instance is equal to the specified object.

GetCustomAttributes(Boolean) GetCustomAttributes(Boolean) GetCustomAttributes(Boolean) GetCustomAttributes(Boolean)

Devuelve todos los atributos personalizados que se aplicaron al AssemblyBuilder actual.Returns all the custom attributes that have been applied to the current AssemblyBuilder.

GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean)

Devuelve todos los atributos personalizados que se aplicaron al AssemblyBuilder actual y que derivan de un tipo de atributo especificado.Returns all the custom attributes that have been applied to the current AssemblyBuilder, and that derive from a specified attribute type.

GetCustomAttributesData() GetCustomAttributesData() GetCustomAttributesData() GetCustomAttributesData()

Devuelve objetos CustomAttributeData que contienen información sobre los atributos que se han aplicado a la clase AssemblyBuilder actual.Returns CustomAttributeData objects that contain information about the attributes that have been applied to the current AssemblyBuilder.

GetDynamicModule(String) GetDynamicModule(String) GetDynamicModule(String) GetDynamicModule(String)

Devuelve el módulo dinámico con el nombre especificado.Returns the dynamic module with the specified name.

GetExportedTypes() GetExportedTypes() GetExportedTypes() GetExportedTypes()

Obtiene los tipos exportados definidos en este ensamblado.Gets the exported types defined in this assembly.

GetFile(String) GetFile(String) GetFile(String) GetFile(String)

Obtiene un objeto FileStream para el archivo especificado en la tabla de archivos del manifiesto de este ensamblado.Gets a FileStream for the specified file in the file table of the manifest of this assembly.

GetFiles() GetFiles() GetFiles() GetFiles()

Obtiene los archivos en la tabla de archivos del manifiesto del ensamblado.Gets the files in the file table of an assembly manifest.

(Inherited from Assembly)
GetFiles(Boolean) GetFiles(Boolean) GetFiles(Boolean) GetFiles(Boolean)

Obtiene los archivos en la tabla de archivos del manifiesto del ensamblado, especificando si deben incluirse módulos de recursos.Gets the files in the file table of an assembly manifest, specifying whether to include resource modules.

GetForwardedTypes() GetForwardedTypes() GetForwardedTypes() GetForwardedTypes() Inherited from Assembly
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Devuelve el código hash de esta instancia.Returns the hash code for this instance.

GetLoadedModules() GetLoadedModules() GetLoadedModules() GetLoadedModules()

Obtiene todos los módulos cargados que forman parte de este ensamblado.Gets all the loaded modules that are part of this assembly.

(Inherited from Assembly)
GetLoadedModules(Boolean) GetLoadedModules(Boolean) GetLoadedModules(Boolean) GetLoadedModules(Boolean)

Devuelve todos los módulos cargados que forman parte de este ensamblado y, opcionalmente, incluye módulos de recursos.Returns all the loaded modules that are part of this assembly, and optionally includes resource modules.

GetManifestResourceInfo(String) GetManifestResourceInfo(String) GetManifestResourceInfo(String) GetManifestResourceInfo(String)

Devuelve información sobre cómo el recurso dado ha persistido.Returns information about how the given resource has been persisted.

GetManifestResourceNames() GetManifestResourceNames() GetManifestResourceNames() GetManifestResourceNames()

Carga el recurso del manifiesto especificado a partir de este ensamblado.Loads the specified manifest resource from this assembly.

GetManifestResourceStream(String) GetManifestResourceStream(String) GetManifestResourceStream(String) GetManifestResourceStream(String)

Carga el recurso del manifiesto especificado a partir de este ensamblado.Loads the specified manifest resource from this assembly.

GetManifestResourceStream(Type, String) GetManifestResourceStream(Type, String) GetManifestResourceStream(Type, String) GetManifestResourceStream(Type, String)

Carga el recurso del manifiesto especificado según el espacio de nombres del tipo especificado a partir de este ensamblado.Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly.

GetModule(String) GetModule(String) GetModule(String) GetModule(String)

Obtiene el módulo especificado en este ensamblado.Gets the specified module in this assembly.

GetModules() GetModules() GetModules() GetModules()

Obtiene todos los módulos que forman parte de este ensamblado.Gets all the modules that are part of this assembly.

(Inherited from Assembly)
GetModules(Boolean) GetModules(Boolean) GetModules(Boolean) GetModules(Boolean)

Obtiene todos los módulos que forman parte de este ensamblado y, opcionalmente, incluye módulos de recursos.Gets all the modules that are part of this assembly, and optionally includes resource modules.

GetName() GetName() GetName() GetName()

Obtiene un AssemblyName para este ensamblado.Gets an AssemblyName for this assembly.

(Inherited from Assembly)
GetName(Boolean) GetName(Boolean) GetName(Boolean) GetName(Boolean)

Obtiene el objeto AssemblyName que se especificó cuando se creó el ensamblado dinámico actual, y establece el código base tal y como se especifica.Gets the AssemblyName that was specified when the current dynamic assembly was created, and sets the code base as specified.

GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

Obtiene información de serialización con todos los datos necesarios para crear una nueva instancia de este ensamblado.Gets serialization information with all of the data needed to reinstantiate this assembly.

(Inherited from Assembly)
GetReferencedAssemblies() GetReferencedAssemblies() GetReferencedAssemblies() GetReferencedAssemblies()

Obtiene una lista incompleta de objetos AssemblyName para los ensamblados a los que hace referencia esta clase AssemblyBuilder.Gets an incomplete list of AssemblyName objects for the assemblies that are referenced by this AssemblyBuilder.

GetSatelliteAssembly(CultureInfo) GetSatelliteAssembly(CultureInfo) GetSatelliteAssembly(CultureInfo) GetSatelliteAssembly(CultureInfo)

Obtiene el ensamblado satélite para la referencia cultural especificada.Gets the satellite assembly for the specified culture.

GetSatelliteAssembly(CultureInfo, Version) GetSatelliteAssembly(CultureInfo, Version) GetSatelliteAssembly(CultureInfo, Version) GetSatelliteAssembly(CultureInfo, Version)

Obtiene la versión especificada del ensamblado satélite para la referencia cultural especificada.Gets the specified version of the satellite assembly for the specified culture.

GetType() GetType() GetType() GetType() Inherited from Assembly
GetType(String) GetType(String) GetType(String) GetType(String)

Obtiene el objeto Type con el nombre especificado en la instancia de ensamblado.Gets the Type object with the specified name in the assembly instance.

(Inherited from Assembly)
GetType(String, Boolean) GetType(String, Boolean) GetType(String, Boolean) 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.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) GetType(String, Boolean, Boolean) GetType(String, Boolean, Boolean) GetType(String, Boolean, Boolean)

Obtiene el tipo especificado de los tipos que se han definido y creado en la clase AssemblyBuilderactual.Gets the specified type from the types that have been defined and created in the current AssemblyBuilder.

GetTypes() GetTypes() GetTypes() GetTypes()

Obtiene los tipos definidos en este ensamblado.Gets the types defined in this assembly.

(Inherited from Assembly)
IsDefined(Type, Boolean) IsDefined(Type, Boolean) IsDefined(Type, Boolean) IsDefined(Type, Boolean)

Devuelve un valor que indica si se aplican una o más instancias del tipo de atributo especificado a este miembro.Returns a value that indicates whether one or more instances of the specified attribute type is applied to this member.

LoadModule(String, Byte[]) LoadModule(String, Byte[]) LoadModule(String, Byte[]) 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.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[]) LoadModule(String, Byte[], Byte[]) LoadModule(String, Byte[], Byte[]) 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.Loads the module, internal to this assembly, with a common object file format (COFF)-based image containing an emitted module, or a resource file. También se cargan los bytes sin formato que representan a los símbolos del módulo.The raw bytes representing the symbols for the module are also loaded.

(Inherited from Assembly)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
Save(String) Save(String) Save(String) Save(String)

Guarda en disco este ensamblado dinámico.Saves this dynamic assembly to disk.

Save(String, PortableExecutableKinds, ImageFileMachine) Save(String, PortableExecutableKinds, ImageFileMachine) Save(String, PortableExecutableKinds, ImageFileMachine) Save(String, PortableExecutableKinds, ImageFileMachine)

Guarda este ensamblado dinámico en disco, especificando la naturaleza del código en los ejecutables del ensamblado y la plataforma de destino.Saves this dynamic assembly to disk, specifying the nature of code in the assembly's executables and the target platform.

SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[])

Establezca un atributo personalizado en este ensamblado mediante el objeto binario especificado de atributo personalizado.Set a custom attribute on this assembly using a specified custom attribute blob.

SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder)

Establezca un atributo personalizado en este ensamblado mediante un generador de atributos personalizados.Set a custom attribute on this assembly using a custom attribute builder.

SetEntryPoint(MethodInfo) SetEntryPoint(MethodInfo) SetEntryPoint(MethodInfo) SetEntryPoint(MethodInfo)

Establece el punto de entrada de este ensamblado dinámico, suponiendo que se está generando una aplicación de consola.Sets the entry point for this dynamic assembly, assuming that a console application is being built.

SetEntryPoint(MethodInfo, PEFileKinds) SetEntryPoint(MethodInfo, PEFileKinds) SetEntryPoint(MethodInfo, PEFileKinds) SetEntryPoint(MethodInfo, PEFileKinds)

Establece el punto de entrada para este ensamblado y define el tipo de archivo ejecutable portable (PE) que se está generando.Sets the entry point for this assembly and defines the type of the portable executable (PE file) being built.

ToString() ToString() ToString() ToString()

Devuelve el nombre completo del ensamblado, también conocido como nombre para mostrar.Returns the full name of the assembly, also known as the display name.

(Inherited from Assembly)

Implementaciones de interfaz explícitas

ICustomAttributeProvider.GetCustomAttributes(Boolean) ICustomAttributeProvider.GetCustomAttributes(Boolean) ICustomAttributeProvider.GetCustomAttributes(Boolean) ICustomAttributeProvider.GetCustomAttributes(Boolean) Inherited from Assembly
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) Inherited from Assembly
ICustomAttributeProvider.IsDefined(Type, Boolean) ICustomAttributeProvider.IsDefined(Type, Boolean) ICustomAttributeProvider.IsDefined(Type, Boolean) ICustomAttributeProvider.IsDefined(Type, Boolean) Inherited from Assembly
_Assembly.GetType() _Assembly.GetType() _Assembly.GetType() _Assembly.GetType()

Devuelve el tipo de la instancia actual.Returns the type of the current instance.

(Inherited from Assembly)
_AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.Maps a set of names to a corresponding set of dispatch identifiers.

_AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr) _AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr) _AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr) _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.Retrieves the type information for an object, which can then be used to get the type information for an interface.

_AssemblyBuilder.GetTypeInfoCount(UInt32) _AssemblyBuilder.GetTypeInfoCount(UInt32) _AssemblyBuilder.GetTypeInfoCount(UInt32) _AssemblyBuilder.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).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) _AssemblyBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _AssemblyBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _AssemblyBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.Provides access to properties and methods exposed by an object.

Eventos

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

Extension Methods

GetExportedTypes(Assembly) GetExportedTypes(Assembly) GetExportedTypes(Assembly) GetExportedTypes(Assembly)
GetModules(Assembly) GetModules(Assembly) GetModules(Assembly) GetModules(Assembly)
GetTypes(Assembly) GetTypes(Assembly) GetTypes(Assembly) GetTypes(Assembly)
GetCustomAttribute(Assembly, Type) GetCustomAttribute(Assembly, Type) GetCustomAttribute(Assembly, Type) GetCustomAttribute(Assembly, Type)

Recupera un atributo personalizado de un tipo especificado que se aplica a un ensamblado concreto.Retrieves a custom attribute of a specified type that is applied to a specified assembly.

GetCustomAttribute<T>(Assembly) GetCustomAttribute<T>(Assembly) GetCustomAttribute<T>(Assembly) GetCustomAttribute<T>(Assembly)

Recupera un atributo personalizado de un tipo especificado que se aplica a un ensamblado concreto.Retrieves a custom attribute of a specified type that is applied to a specified assembly.

GetCustomAttributes(Assembly) GetCustomAttributes(Assembly) GetCustomAttributes(Assembly) GetCustomAttributes(Assembly)

Recupera una colección de atributos personalizados que se aplican a un ensamblado especificado.Retrieves a collection of custom attributes that are applied to a specified assembly.

GetCustomAttributes(Assembly, Type) GetCustomAttributes(Assembly, Type) GetCustomAttributes(Assembly, Type) GetCustomAttributes(Assembly, Type)

Recupera una colección de atributos personalizados de un tipo especificado que se aplican a un ensamblado concreto.Retrieves a collection of custom attributes of a specified type that are applied to a specified assembly.

GetCustomAttributes<T>(Assembly) GetCustomAttributes<T>(Assembly) GetCustomAttributes<T>(Assembly) GetCustomAttributes<T>(Assembly)

Recupera una colección de atributos personalizados de un tipo especificado que se aplican a un ensamblado concreto.Retrieves a collection of custom attributes of a specified type that are applied to a specified assembly.

IsDefined(Assembly, Type) IsDefined(Assembly, Type) IsDefined(Assembly, Type) IsDefined(Assembly, Type)

Indica si se deben aplicar atributos personalizados de un tipo especificado a un ensamblado especificado.Indicates whether custom attributes of a specified type are applied to a specified assembly.

TryGetRawMetadata(Assembly, Byte*, Int32) TryGetRawMetadata(Assembly, Byte*, Int32) TryGetRawMetadata(Assembly, Byte*, Int32) TryGetRawMetadata(Assembly, Byte*, Int32)

Seguridad

ReflectionPermission
Cuando se invoca en tiempo de ejecución a través de mecanismos como InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]).when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Se aplica a

Consulte también: