AssemblyBuilder Classe

Definizione

Definisce e rappresenta un assembly dinamico.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
Ereditarietà
AssemblyBuilder
Attributi
Implementazioni

Esempi

Nell'esempio di codice seguente viene illustrato come definire un assembly dinamico con un modulo.The following code example shows how to define a dynamic assembly with one module. Il modulo nell'assembly di esempio contiene un tipo, MyDynamicType, che dispone di un campo privato, una proprietà che ottiene e imposta il campo privato, i costruttori che inizializzano il campo privato e un metodo che moltiplica un numero fornito dall'utente dal campo privato e restituisce il risultato.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.RunAndSaveviene specificato al momento della creazione dell'assembly.AssemblyBuilderAccess.RunAndSave is specified when the assembly is created. Il codice dell'assembly viene utilizzato immediatamente e l'assembly viene salvato su disco in modo che possa essere esaminato con Ildasm. exe (DISASSEMBLER il) o utilizzato in un altro programma.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.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

Commenti

Un assembly dinamico è un assembly creato mediante le API di Reflection Emit.A dynamic assembly is an assembly that is created using the Reflection Emit APIs. I moduli dinamici nell'assembly vengono salvati quando l'assembly dinamico viene salvato utilizzando il Save metodo.The dynamic modules in the assembly are saved when the dynamic assembly is saved using the Save method. Per generare un eseguibile, SetEntryPoint è necessario chiamare il metodo per identificare il metodo che rappresenta il punto di ingresso dell'assembly.To generate an executable, the SetEntryPoint method must be called to identify the method that is the entry point to the assembly. Per impostazione predefinita, gli assembly vengono salvati come dll, SetEntryPoint a meno che il metodo non richieda la generazione di un'applicazione console o di un'applicazione basata su Windows.Assemblies are saved as DLLs by default, unless the SetEntryPoint method requests the generation of a console application or a Windows-based application.

Se un assembly dinamico contiene più di un modulo dinamico, il nome del file manifesto dell'assembly deve corrispondere al nome del modulo specificato come primo argomento DefineDynamicModule del metodo.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.

Alcuni metodi della classe di Assembly base, GetModules ad esempio e GetLoadedModules, non funzioneranno correttamente quando vengono chiamati AssemblyBuilder da oggetti.Some methods on the base Assembly class, such as GetModules and GetLoadedModules, will not work correctly when called from AssemblyBuilder objects. È possibile caricare l'assembly dinamico definito e chiamare i metodi nell'assembly caricato.You can load the defined dynamic assembly and call the methods on the loaded assembly. Per assicurarsi, ad esempio, che i moduli delle risorse siano inclusi nell'elenco dei moduli GetModules restituiti, chiamare Assembly sull'oggetto caricato.For example, to ensure that resource modules are included in the returned module list, call GetModules on the loaded Assembly object.

La firma di un assembly dinamico con KeyPair non è valida fino a quando l'assembly non viene salvato su disco.The signing of a dynamic assembly using KeyPair is not effective until the assembly is saved to disk. I nomi sicuri non funzioneranno quindi con gli assembly dinamici temporanei.So, strong names will not work with transient dynamic assemblies.

Per ottenere un AssemblyBuilder oggetto, usare il AppDomain.DefineDynamicAssembly metodo.To get an AssemblyBuilder object, use the AppDomain.DefineDynamicAssembly method.

Scenari di assembly dinamici della Reflection EmitReflection emit dynamic assembly scenarios

Di seguito sono riportati alcuni aspetti da considerare quando si AssemblyBuilder usa la classe per creare assembly dinamici.The following are some things to consider when using the AssemblyBuilder class to create dynamic assemblies.

Moduli dinamiciDynamic modules

Reflection Emit supporta la creazione di moduli dinamici definiti in assembly dinamici.Reflection emit supports the creation of dynamic modules defined in dynamic assemblies. Un modulo dinamico creato in un assembly dinamico può essere temporaneo o persistente.A dynamic module created in a dynamic assembly can be transient or persistable.

Restrizioni sui riferimenti ai tipiRestrictions on type references

Gli assembly possono fare riferimento ai tipi definiti in un altro assembly.Assemblies can reference types defined in another assembly. Un assembly dinamico temporaneo può fare riferimento in modo sicuro ai tipi definiti in un altro assembly dinamico temporaneo, un assembly dinamico persistente o un assembly statico.A transient dynamic assembly can safely reference types defined in another transient dynamic assembly, a persistable dynamic assembly, or a static assembly. Tuttavia, il Common Language Runtime non consente a un modulo dinamico persistente di fare riferimento a un tipo definito in un modulo dinamico temporaneo.However, the common language runtime does not allow a persistable dynamic module to reference a type defined in a transient dynamic module. Questo perché quando il modulo dinamico persistente viene caricato dopo essere stato salvato su disco, il runtime non è in grado di risolvere i riferimenti ai tipi definiti nel modulo dinamico temporaneo.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.

Limitazioni relative alla creazione di domini applicazione remotiRestrictions on emitting to remote application domains

Per alcuni scenari è necessario che un assembly dinamico venga creato ed eseguito in un dominio applicazione remoto.Some scenarios require a dynamic assembly to be created and executed in a remote application domain. La reflection emit non consente l'emissione di un assembly dinamico direttamente in un dominio applicazione remoto.Reflection emit does not allow a dynamic assembly to be emitted directly to a remote application domain. La soluzione consiste nel creare l'assembly dinamico nel dominio applicazione corrente, salvare l'assembly dinamico generato su disco e quindi caricare l'assembly dinamico nel dominio dell'applicazione 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.

Modalità di accesso a assembly dinamiciDynamic assembly access modes

È possibile creare assembly dinamici utilizzando una delle modalità di accesso seguenti:Dynamic assemblies can be created using one of the following access modes:

  • AssemblyBuilderAccess.Run

    L'assembly dinamico rappresentato da un AssemblyBuilder oggetto è temporaneo.The dynamic assembly represented by an AssemblyBuilder object is transient. L'assembly dinamico può essere utilizzato solo per eseguire il codice generato.The dynamic assembly can only be used to execute the emitted code.

  • AssemblyBuilderAccess.Save

    L'assembly dinamico rappresentato da un AssemblyBuilder oggetto è permanente, ma non può essere eseguito fino a quando il file eseguibile portabile (PE) salvato non è stato caricato dal 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

    L'assembly dinamico rappresentato da un AssemblyBuilder oggetto è permanente, ma può anche essere eseguito prima e/o dopo che l'assembly viene salvato su 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.

È necessario specificare la modalità di accesso specificando il AssemblyBuilderAccess valore appropriato nella chiamata AssemblyBuilder.DefineDynamicAssembly al metodo quando l'assembly dinamico è definito e non può essere modificato in un secondo momento.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. Il runtime usa la modalità di accesso di un assembly dinamico per ottimizzare la rappresentazione interna dell'assembly.The runtime uses the access mode of a dynamic assembly to optimize the assembly's internal representation.

Costruttori

AssemblyBuilder()

Proprietà

CodeBase

Ottiene la posizione dell'assembly come specificata in origine, ad esempio in un oggetto AssemblyName.Gets the location of the assembly, as specified originally (such as in an AssemblyName object).

CustomAttributes

Ottiene una raccolta che contiene gli attributi personalizzati di questo assembly.Gets a collection that contains this assembly's custom attributes.

(Ereditato da Assembly)
DefinedTypes
EntryPoint

Restituisce il punto di ingresso dell'assembly.Returns the entry point of this assembly.

EscapedCodeBase

Ottiene l'URI, inclusi i caratteri di escape, che rappresenta la codebase.Gets the URI, including escape characters, that represents the codebase.

(Ereditato da Assembly)
Evidence

Ottiene l'evidenza per questo assembly.Gets the evidence for this assembly.

ExportedTypes

Ottiene una raccolta dei tipi pubblici definiti in questo assembly visibili all'esterno dell'assembly.Gets a collection of the public types defined in this assembly that are visible outside the assembly.

(Ereditato da Assembly)
FullName

Ottiene il nome visualizzato dell'assembly dinamico corrente.Gets the display name of the current dynamic assembly.

GlobalAssemblyCache

Ottiene un valore che indica se l'assembly è stato caricato dalla Global Assembly Cache.Gets a value that indicates whether the assembly was loaded from the global assembly cache.

HostContext

Ottiene il contesto host in cui viene creato l'assembly dinamico.Gets the host context where the dynamic assembly is being created.

ImageRuntimeVersion

Ottiene la versione di CLR (Common Language Runtime) che verrà salvata nel file che contiene il manifesto.Gets the version of the common language runtime that will be saved in the file containing the manifest.

IsCollectible

Ottiene un valore che indica se questo assembly viene mantenuto in un AssemblyLoadContext ritirabile.Gets a value that indicates whether this assembly is held in a collectible AssemblyLoadContext.

(Ereditato da Assembly)
IsDynamic

Ottiene un valore che indica che l'assembly corrente è un assembly dinamico.Gets a value that indicates that the current assembly is a dynamic assembly.

IsFullyTrusted

Ottiene un valore che indica se l'assembly corrente viene caricato con attendibilità totale.Gets a value that indicates whether the current assembly is loaded with full trust.

(Ereditato da Assembly)
Location

Ottiene il percorso, in formato codebase, del file caricato che contiene il manifesto se non ne viene creata una copia shadow.Gets the location, in codebase format, of the loaded file that contains the manifest if it is not shadow-copied.

ManifestModule

Ottiene il modulo nell'oggetto AssemblyBuilder corrente che contiene il manifesto dell'assembly.Gets the module in the current AssemblyBuilder that contains the assembly manifest.

Modules
PermissionSet

Ottiene la concessione dell'assembly dinamico corrente.Gets the grant set of the current dynamic assembly.

ReflectionOnly

Ottiene un valore che indica se l'assembly dinamico si trova nel contesto Reflection-Only.Gets a value indicating whether the dynamic assembly is in the reflection-only context.

SecurityRuleSet

Ottiene un valore che indica il set di regole di sicurezza applicato da Common Language Runtime (CLR) per questo assembly.Gets a value that indicates which set of security rules the common language runtime (CLR) enforces for this assembly.

Metodi

AddResourceFile(String, String)

Aggiunge un file di risorse esistenti a questo assembly.Adds an existing resource file to this assembly.

AddResourceFile(String, String, ResourceAttributes)

Aggiunge un file di risorse esistenti a questo assembly.Adds an existing resource file to this assembly.

CreateInstance(String)

Individua il tipo specificato in questo assembly e ne crea un'istanza usando l'attivatore di sistema e consentendo la ricerca con distinzione tra maiuscole e minuscole.Locates the specified type from this assembly and creates an instance of it using the system activator, using case-sensitive search.

(Ereditato da Assembly)
CreateInstance(String, Boolean)

Individua il tipo specificato in questo assembly e ne crea un'istanza usando l'attivatore di sistema e consentendo la ricerca con distinzione facoltativa tra maiuscole e minuscole.Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search.

(Ereditato da Assembly)
CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

Individua il tipo specificato in questo assembly e ne crea un'istanza usando l'attivatore di sistema, consentendo la ricerca con distinzione facoltativa tra maiuscole e minuscole e usando le impostazioni cultura, gli argomenti e gli attributi di attivazione e di binding specificati.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.

(Ereditato da Assembly)
DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)

Definisce un assembly dinamico con il nome e i diritti di accesso specificati.Defines a dynamic assembly that has the specified name and access rights.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)

Definisce un nuovo assembly con il nome, i diritti di accesso e gli attributi specificati.Defines a new assembly that has the specified name, access rights, and attributes.

DefineDynamicModule(String)

Definisce un modulo dinamico temporaneo denominato nell'assembly.Defines a named transient dynamic module in this assembly.

DefineDynamicModule(String, Boolean)

Definisce un modulo dinamico temporaneo denominato nell'assembly e specifica se le informazioni sui simboli devono essere emesse.Defines a named transient dynamic module in this assembly and specifies whether symbol information should be emitted.

DefineDynamicModule(String, String)

Definisce un modulo dinamico persistente con il nome dato che verrà salvato nel file specificato.Defines a persistable dynamic module with the given name that will be saved to the specified file. Non viene emessa alcuna informazione sui simboli.No symbol information is emitted.

DefineDynamicModule(String, String, Boolean)

Definisce un modulo dinamico persistente, specificando il nome del modulo, il nome del file in cui modulo verrà salvato e la creazione delle informazioni sui simboli tramite il writer dei simboli predefinito.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)

Definisce una risorsa gestita autonoma per l'assembly con l'attributo di risorsa pubblico predefinito.Defines a standalone managed resource for this assembly with the default public resource attribute.

DefineResource(String, String, String, ResourceAttributes)

Definisce una risorsa gestita autonoma per l'assembly.Defines a standalone managed resource for this assembly. È possibile specificare gli attributi per la risorsa gestita.Attributes can be specified for the managed resource.

DefineUnmanagedResource(Byte[])

Definisce una risorsa non gestita per questo assembly come BLOB opaco di byte.Defines an unmanaged resource for this assembly as an opaque blob of bytes.

DefineUnmanagedResource(String)

Definisce un file di risorse non gestite per l'assembly, dato il nome del file di risorse.Defines an unmanaged resource file for this assembly given the name of the resource file.

DefineVersionInfoResource()

Definisce una risorsa di informazioni di versione non gestita usando le informazioni specificate nell'oggetto AssemblyName dell'assembly e gli attributi personalizzati dell'assembly.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)

Definisce una risorsa di informazioni sulla versione non gestita per questo assembly insieme alle specifiche date.Defines an unmanaged version information resource for this assembly with the given specifications.

Equals(Object)

Restituisce un valore che indica se questa istanza è uguale all'oggetto specificato.Returns a value that indicates whether this instance is equal to the specified object.

GetCustomAttributes(Boolean)

Restituisce tutti gli attributi personalizzati applicati all'oggetto AssemblyBuilder corrente.Returns all the custom attributes that have been applied to the current AssemblyBuilder.

GetCustomAttributes(Type, Boolean)

Restituisce tutti gli attributi personalizzati applicati all'oggetto AssemblyBuilder corrente e che derivano da un tipo di attributo specificato.Returns all the custom attributes that have been applied to the current AssemblyBuilder, and that derive from a specified attribute type.

GetCustomAttributesData()

Restituisce oggetti CustomAttributeData che contengono informazioni sugli attributi applicati all'oggetto AssemblyBuilder corrente.Returns CustomAttributeData objects that contain information about the attributes that have been applied to the current AssemblyBuilder.

GetDynamicModule(String)

Restituisce il modulo dinamico con il nome specificato.Returns the dynamic module with the specified name.

GetExportedTypes()

Ottiene i tipi esportati definiti nell'assembly.Gets the exported types defined in this assembly.

GetFile(String)

Ottiene un oggetto FileStream per il file specificato nella tabella file del manifesto dell'assembly.Gets a FileStream for the specified file in the file table of the manifest of this assembly.

GetFiles()

Ottiene i file della tabella file di un manifesto dell'assembly.Gets the files in the file table of an assembly manifest.

(Ereditato da Assembly)
GetFiles(Boolean)

Ottiene i file della tabella file di un manifesto dell'assembly, specificando se includere i moduli delle risorse.Gets the files in the file table of an assembly manifest, specifying whether to include resource modules.

GetForwardedTypes() (Ereditato da Assembly)
GetHashCode()

Restituisce il codice hash per l'istanza.Returns the hash code for this instance.

GetLoadedModules()

Ottiene tutti i moduli caricati che fanno parte di questo assembly.Gets all the loaded modules that are part of this assembly.

(Ereditato da Assembly)
GetLoadedModules(Boolean)

Restituisce tutti i moduli caricati che fanno parte di questo assembly e, facoltativamente, comprende i moduli delle risorse.Returns all the loaded modules that are part of this assembly, and optionally includes resource modules.

GetManifestResourceInfo(String)

Restituisce informazioni sul modo in cui la risorsa specificata è stata resa persistente.Returns information about how the given resource has been persisted.

GetManifestResourceNames()

Carica la risorsa del manifesto specificata da questo assembly.Loads the specified manifest resource from this assembly.

GetManifestResourceStream(String)

Carica la risorsa del manifesto specificata da questo assembly.Loads the specified manifest resource from this assembly.

GetManifestResourceStream(Type, String)

Carica la risorsa del manifesto specificata, definita per l'ambito dallo spazio dei nomi del tipo specificato, da questo assembly.Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly.

GetModule(String)

Ottiene il modulo specificato in questo assembly.Gets the specified module in this assembly.

GetModules()

Ottiene tutti i moduli che fanno parte di questo assembly.Gets all the modules that are part of this assembly.

(Ereditato da Assembly)
GetModules(Boolean)

Ottiene tutti i moduli che fanno parte di questo assembly e, facoltativamente, comprende i moduli delle risorse.Gets all the modules that are part of this assembly, and optionally includes resource modules.

GetName()

Ottiene un oggetto AssemblyName per questo assembly.Gets an AssemblyName for this assembly.

(Ereditato da Assembly)
GetName(Boolean)

Ottiene l'oggetto AssemblyName specificato alla creazione dell'assembly dinamico corrente e imposta la codebase come specificato.Gets the AssemblyName that was specified when the current dynamic assembly was created, and sets the code base as specified.

GetObjectData(SerializationInfo, StreamingContext)

Ottiene le informazioni sulla serializzazione con tutti i dati necessari per creare una nuova istanza di questo assembly.Gets serialization information with all of the data needed to reinstantiate this assembly.

(Ereditato da Assembly)
GetReferencedAssemblies()

Ottiene un elenco incompleto di oggetti AssemblyName per gli assembly a cui fa riferimento questo oggetto AssemblyBuilder.Gets an incomplete list of AssemblyName objects for the assemblies that are referenced by this AssemblyBuilder.

GetSatelliteAssembly(CultureInfo)

Ottiene l'assembly satellite per le impostazioni cultura specificate.Gets the satellite assembly for the specified culture.

GetSatelliteAssembly(CultureInfo, Version)

Ottiene la versione specificata dell'assembly satellite per le impostazioni cultura specificate.Gets the specified version of the satellite assembly for the specified culture.

GetType() (Ereditato da Assembly)
GetType(String)

Ottiene l'oggetto Type con il nome specificato nell'istanza dell'assembly.Gets the Type object with the specified name in the assembly instance.

(Ereditato da Assembly)
GetType(String, Boolean)

Ottiene l'oggetto Type con il nome specificato nell'istanza dell'assembly e facoltativamente genera un'eccezione se il tipo non viene trovato.Gets the Type object with the specified name in the assembly instance and optionally throws an exception if the type is not found.

(Ereditato da Assembly)
GetType(String, Boolean, Boolean)

Ottiene il tipo specificato dai tipi definiti e creati nell'oggetto AssemblyBuilder corrente.Gets the specified type from the types that have been defined and created in the current AssemblyBuilder.

GetTypes()

Ottiene i tipi definiti in questo assembly.Gets the types defined in this assembly.

(Ereditato da Assembly)
IsDefined(Type, Boolean)

Restituisce un valore che indica se a questo membro sono state applicate una o più istanze del tipo di attributo specificato.Returns a value that indicates whether one or more instances of the specified attribute type is applied to this member.

LoadModule(String, Byte[])

Carica il modulo, interno all'assembly, con un'immagine in formato COFF (Common Object File Format) contenente un modulo generato o un file di risorse.Loads the module, internal to this assembly, with a common object file format (COFF)-based image containing an emitted module, or a resource file.

(Ereditato da Assembly)
LoadModule(String, Byte[], Byte[])

Carica il modulo, interno all'assembly, con un'immagine in formato COFF (Common Object File Format) contenente un modulo generato o un file di risorse.Loads the module, internal to this assembly, with a common object file format (COFF)-based image containing an emitted module, or a resource file. Vengono caricati anche i byte non elaborati che rappresentano i simboli per il modulo.The raw bytes representing the symbols for the module are also loaded.

(Ereditato da Assembly)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.Creates a shallow copy of the current Object.

(Ereditato da Object)
Save(String)

Salva l'assembly dinamico sul disco.Saves this dynamic assembly to disk.

Save(String, PortableExecutableKinds, ImageFileMachine)

Salva l'assembly dinamico su disco, specificando la natura del codice nei file eseguibili dell'assembly e la piattaforma di destinazione.Saves this dynamic assembly to disk, specifying the nature of code in the assembly's executables and the target platform.

SetCustomAttribute(ConstructorInfo, Byte[])

Imposta un attributo personalizzato nell'assembly usando un BLOB di attributi personalizzati specificato.Set a custom attribute on this assembly using a specified custom attribute blob.

SetCustomAttribute(CustomAttributeBuilder)

Impostare un attributo personalizzato nell'assembly usando un generatore di attributi personalizzati.Set a custom attribute on this assembly using a custom attribute builder.

SetEntryPoint(MethodInfo)

Imposta il punto di ingresso dell'assembly dinamico, presupponendo che sia in corso la compilazione di un'applicazione console.Sets the entry point for this dynamic assembly, assuming that a console application is being built.

SetEntryPoint(MethodInfo, PEFileKinds)

Imposta il punto di ingresso dell'assembly e definisce il tipo del file eseguibile di tipo PE in corso di compilazione.Sets the entry point for this assembly and defines the type of the portable executable (PE file) being built.

ToString()

Restituisce il nome completo dell'assembly, noto anche come nome visualizzato.Returns the full name of the assembly, also known as the display name.

(Ereditato da Assembly)

Eventi

ModuleResolve

Si verifica quando il caricatore della classe Common Language Runtime non è in grado di risolvere un riferimento a un modulo interno di un assembly in modo normale.Occurs when the common language runtime class loader cannot resolve a reference to an internal module of an assembly through normal means.

(Ereditato da Assembly)

Implementazioni dell'interfaccia esplicita

_Assembly.GetType()

Restituisce il tipo dell'istanza corrente.Returns the type of the current instance.

(Ereditato da Assembly)
_AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Esegue il mapping di un set di nomi a un set corrispondente di ID dispatch.Maps a set of names to a corresponding set of dispatch identifiers.

_AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera le informazioni sul tipo relative a un oggetto che può quindi essere usato per ottenere informazioni sul tipo relative a un'interfaccia.Retrieves the type information for an object, which can then be used to get the type information for an interface.

_AssemblyBuilder.GetTypeInfoCount(UInt32)

Recupera il numero delle interfacce di informazioni sul tipo fornite da un oggetto (0 o 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)

Fornisce l'accesso a proprietà e metodi esposti da un oggetto.Provides access to properties and methods exposed by an object.

ICustomAttributeProvider.GetCustomAttributes(Boolean) (Ereditato da Assembly)
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) (Ereditato da Assembly)
ICustomAttributeProvider.IsDefined(Type, Boolean) (Ereditato da Assembly)

Metodi di estensione

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

Recupera una attributo personalizzato di un tipo specificato che viene applicato a un assembly specificato.Retrieves a custom attribute of a specified type that is applied to a specified assembly.

GetCustomAttribute<T>(Assembly)

Recupera una attributo personalizzato di un tipo specificato che viene applicato a un assembly specificato.Retrieves a custom attribute of a specified type that is applied to a specified assembly.

GetCustomAttributes(Assembly)

Recupera una raccolta di attributi personalizzati che vengono applicati a un assembly specificato.Retrieves a collection of custom attributes that are applied to a specified assembly.

GetCustomAttributes(Assembly, Type)

Recupera una raccolta di attributi personalizzati di un tipo specificato che vengono applicati a un assembly specificato.Retrieves a collection of custom attributes of a specified type that are applied to a specified assembly.

GetCustomAttributes<T>(Assembly)

Recupera una raccolta di attributi personalizzati di un tipo specificato che vengono applicati a un assembly specificato.Retrieves a collection of custom attributes of a specified type that are applied to a specified assembly.

IsDefined(Assembly, Type)

Indica se vengono applicati attributi personalizzati del tipo specificato a un assembly specificato.Indicates whether custom attributes of a specified type are applied to a specified assembly.

TryGetRawMetadata(Assembly, Byte*, Int32)

Sicurezza

ReflectionPermission
Quando viene richiamato ad associazione tardiva tramite InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])meccanismi come.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumerazione associata: MemberAccess.Associated enumeration: MemberAccess.

Si applica a

Vedi anche