AssemblyBuilder Classe

Définition

Définit et représente un assembly dynamique.

public ref class AssemblyBuilder sealed : System::Reflection::Assembly
public ref class AssemblyBuilder abstract : System::Reflection::Assembly
public ref class AssemblyBuilder sealed : System::Reflection::Assembly, System::Runtime::InteropServices::_AssemblyBuilder
public sealed class AssemblyBuilder : System.Reflection.Assembly
public abstract class AssemblyBuilder : System.Reflection.Assembly
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
public sealed class AssemblyBuilder : System.Reflection.Assembly, System.Runtime.InteropServices._AssemblyBuilder
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyBuilder : System.Reflection.Assembly, System.Runtime.InteropServices._AssemblyBuilder
type AssemblyBuilder = class
    inherit Assembly
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
type AssemblyBuilder = class
    inherit Assembly
    interface _AssemblyBuilder
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type AssemblyBuilder = class
    inherit Assembly
    interface _AssemblyBuilder
Public NotInheritable Class AssemblyBuilder
Inherits Assembly
Public MustInherit Class AssemblyBuilder
Inherits Assembly
Public NotInheritable Class AssemblyBuilder
Inherits Assembly
Implements _AssemblyBuilder
Héritage
AssemblyBuilder
Attributs
Implémente

Exemples

L’exemple de code suivant montre comment définir et utiliser un assembly dynamique. L’exemple d’assembly contient un type, MyDynamicType, qui a un champ privé, une propriété qui obtient et définit le champ privé, des constructeurs qui initialisent le champ privé et une méthode qui multiplie un nombre fourni par l’utilisateur par la valeur du champ privé et retourne le résultat.

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

void main()
{
    // This code creates an assembly that contains one type,
    // named "MyDynamicType", that has a private field, a property
    // that gets and sets the private field, constructors that
    // initialize the private field, and a method that multiplies
    // a user-supplied number by the private field value and returns
    // the result. In Visual C++ the type might look like this:
    /*
      public ref class MyDynamicType
      {
      private:
          int m_number;

      public:
          MyDynamicType() : m_number(42) {};
          MyDynamicType(int initNumber) : m_number(initNumber) {};
      
          property int Number
          {
              int get() { return m_number; }
              void set(int value) { m_number = value; }
          }

          int MyMethod(int multiplier)
          {
              return m_number * multiplier;
          }
      };
    */
      
    AssemblyName^ aName = gcnew AssemblyName("DynamicAssemblyExample");
    AssemblyBuilder^ ab = 
        AssemblyBuilder::DefineDynamicAssembly(
            aName, 
            AssemblyBuilderAccess::Run);

    // The module name is usually the same as the assembly name
    ModuleBuilder^ mb = 
        ab->DefineDynamicModule(aName->Name);
      
    TypeBuilder^ tb = mb->DefineType(
        "MyDynamicType", 
         TypeAttributes::Public);

    // Add a private field of type int (Int32).
    FieldBuilder^ fbNumber = tb->DefineField(
        "m_number", 
        int::typeid, 
        FieldAttributes::Private);

    // Define a constructor that takes an integer argument and 
    // stores it in the private field. 
    array<Type^>^ parameterTypes = { int::typeid };
    ConstructorBuilder^ ctor1 = tb->DefineConstructor(
        MethodAttributes::Public, 
        CallingConventions::Standard, 
        parameterTypes);

    ILGenerator^ ctor1IL = ctor1->GetILGenerator();
    // For a constructor, argument zero is a reference to the new
    // instance. Push it on the stack before calling the base
    // class constructor. Specify the default constructor of the 
    // base class (System::Object) by passing an empty array of 
    // types (Type::EmptyTypes) to GetConstructor.
    ctor1IL->Emit(OpCodes::Ldarg_0);
    ctor1IL->Emit(OpCodes::Call, 
        Object::typeid->GetConstructor(Type::EmptyTypes));
    // Push the instance on the stack before pushing the argument
    // that is to be assigned to the private field m_number.
    ctor1IL->Emit(OpCodes::Ldarg_0);
    ctor1IL->Emit(OpCodes::Ldarg_1);
    ctor1IL->Emit(OpCodes::Stfld, fbNumber);
    ctor1IL->Emit(OpCodes::Ret);

    // Define a default constructor that supplies a default value
    // for the private field. For parameter types, pass the empty
    // array of types or pass nullptr.
    ConstructorBuilder^ ctor0 = tb->DefineConstructor(
        MethodAttributes::Public, 
        CallingConventions::Standard, 
        Type::EmptyTypes);

    ILGenerator^ ctor0IL = ctor0->GetILGenerator();
    ctor0IL->Emit(OpCodes::Ldarg_0);
    ctor0IL->Emit(OpCodes::Call, 
        Object::typeid->GetConstructor(Type::EmptyTypes));
    // For a constructor, argument zero is a reference to the new
    // instance. Push it on the stack before pushing the default
    // value on the stack.
    ctor0IL->Emit(OpCodes::Ldarg_0);
    ctor0IL->Emit(OpCodes::Ldc_I4_S, 42);
    ctor0IL->Emit(OpCodes::Stfld, fbNumber);
    ctor0IL->Emit(OpCodes::Ret);

    // Define a property named Number that gets and sets the private 
    // field.
    //
    // The last argument of DefineProperty is nullptr, because the
    // property has no parameters. (If you don't specify nullptr, you must
    // specify an array of Type objects. For a parameterless property,
    // use the built-in array with no elements: Type::EmptyTypes)
    PropertyBuilder^ pbNumber = tb->DefineProperty(
        "Number", 
        PropertyAttributes::HasDefault, 
        int::typeid, 
        nullptr);
      
    // The property "set" and property "get" methods require a special
    // set of attributes.
    MethodAttributes getSetAttr = MethodAttributes::Public | 
        MethodAttributes::SpecialName | MethodAttributes::HideBySig;

    // Define the "get" accessor method for Number. The method returns
    // an integer and has no arguments. (Note that nullptr could be 
    // used instead of Types::EmptyTypes)
    MethodBuilder^ mbNumberGetAccessor = tb->DefineMethod(
        "get_Number", 
        getSetAttr, 
        int::typeid, 
        Type::EmptyTypes);
      
    ILGenerator^ numberGetIL = mbNumberGetAccessor->GetILGenerator();
    // For an instance property, argument zero is the instance. Load the 
    // instance, then load the private field and return, leaving the
    // field value on the stack.
    numberGetIL->Emit(OpCodes::Ldarg_0);
    numberGetIL->Emit(OpCodes::Ldfld, fbNumber);
    numberGetIL->Emit(OpCodes::Ret);
    
    // Define the "set" accessor method for Number, which has no return
    // type and takes one argument of type int (Int32).
    MethodBuilder^ mbNumberSetAccessor = tb->DefineMethod(
        "set_Number", 
        getSetAttr, 
        nullptr, 
        gcnew array<Type^> { int::typeid });
      
    ILGenerator^ numberSetIL = mbNumberSetAccessor->GetILGenerator();
    // Load the instance and then the numeric argument, then store the
    // argument in the field.
    numberSetIL->Emit(OpCodes::Ldarg_0);
    numberSetIL->Emit(OpCodes::Ldarg_1);
    numberSetIL->Emit(OpCodes::Stfld, fbNumber);
    numberSetIL->Emit(OpCodes::Ret);
      
    // Last, map the "get" and "set" accessor methods to the 
    // PropertyBuilder. The property is now complete. 
    pbNumber->SetGetMethod(mbNumberGetAccessor);
    pbNumber->SetSetMethod(mbNumberSetAccessor);

    // Define a method that accepts an integer argument and returns
    // the product of that integer and the private field m_number. This
    // time, the array of parameter types is created on the fly.
    MethodBuilder^ meth = tb->DefineMethod(
        "MyMethod", 
        MethodAttributes::Public, 
        int::typeid, 
        gcnew array<Type^> { int::typeid });

    ILGenerator^ methIL = meth->GetILGenerator();
    // To retrieve the private instance field, load the instance it
    // belongs to (argument zero). After loading the field, load the 
    // argument one and then multiply. Return from the method with 
    // the return value (the product of the two numbers) on the 
    // execution stack.
    methIL->Emit(OpCodes::Ldarg_0);
    methIL->Emit(OpCodes::Ldfld, fbNumber);
    methIL->Emit(OpCodes::Ldarg_1);
    methIL->Emit(OpCodes::Mul);
    methIL->Emit(OpCodes::Ret);

    // Finish the type->
    Type^ t = tb->CreateType();

    // Because AssemblyBuilderAccess includes Run, the code can be
    // executed immediately. Start by getting reflection objects for
    // the method and the property.
    MethodInfo^ mi = t->GetMethod("MyMethod");
    PropertyInfo^ pi = t->GetProperty("Number");
  
    // Create an instance of MyDynamicType using the default 
    // constructor. 
    Object^ o1 = Activator::CreateInstance(t);

    // Display the value of the property, then change it to 127 and 
    // display it again. Use nullptr to indicate that the property
    // has no index.
    Console::WriteLine("o1->Number: {0}", pi->GetValue(o1, nullptr));
    pi->SetValue(o1, 127, nullptr);
    Console::WriteLine("o1->Number: {0}", pi->GetValue(o1, nullptr));

    // Call MyMethod, passing 22, and display the return value, 22
    // times 127. Arguments must be passed as an array, even when
    // there is only one.
    array<Object^>^ arguments = { 22 };
    Console::WriteLine("o1->MyMethod(22): {0}", 
        mi->Invoke(o1, arguments));

    // Create an instance of MyDynamicType using the constructor
    // that specifies m_Number. The constructor is identified by
    // matching the types in the argument array. In this case, 
    // the argument array is created on the fly. Display the 
    // property value.
    Object^ o2 = Activator::CreateInstance(t, 
        gcnew array<Object^> { 5280 });
    Console::WriteLine("o2->Number: {0}", pi->GetValue(o2, nullptr));
};

/* This code produces the following output:

o1->Number: 42
o1->Number: 127
o1->MyMethod(22): 2794
o2->Number: 5280
 */
using System;
using System.Reflection;
using System.Reflection.Emit;

class DemoAssemblyBuilder
{
    public static void Main()
    {
        // This code creates an assembly that contains one type,
        // named "MyDynamicType", that has a private field, a property
        // that gets and sets the private field, constructors that
        // initialize the private field, and a method that multiplies
        // a user-supplied number by the private field value and returns
        // the result. In C# the type might look like this:
        /*
        public class MyDynamicType
        {
            private int m_number;

            public MyDynamicType() : this(42) {}
            public MyDynamicType(int initNumber)
            {
                m_number = initNumber;
            }

            public int Number
            {
                get { return m_number; }
                set { m_number = value; }
            }

            public int MyMethod(int multiplier)
            {
                return m_number * multiplier;
            }
        }
        */

        var aName = new AssemblyName("DynamicAssemblyExample");
        AssemblyBuilder ab =
            AssemblyBuilder.DefineDynamicAssembly(
                aName,
                AssemblyBuilderAccess.Run);

        // The module name is usually the same as the assembly name.
        ModuleBuilder mb = ab.DefineDynamicModule(aName.Name ?? "DynamicAssemblyExample");

        TypeBuilder tb = mb.DefineType(
            "MyDynamicType",
             TypeAttributes.Public);

        // Add a private field of type int (Int32).
        FieldBuilder fbNumber = tb.DefineField(
            "m_number",
            typeof(int),
            FieldAttributes.Private);

        // Define a constructor that takes an integer argument and
        // stores it in the private field.
        Type[] parameterTypes = { typeof(int) };
        ConstructorBuilder ctor1 = tb.DefineConstructor(
            MethodAttributes.Public,
            CallingConventions.Standard,
            parameterTypes);

        ILGenerator ctor1IL = ctor1.GetILGenerator();
        // For a constructor, argument zero is a reference to the new
        // instance. Push it on the stack before calling the base
        // class constructor. Specify the default constructor of the
        // base class (System.Object) by passing an empty array of
        // types (Type.EmptyTypes) to GetConstructor.
        ctor1IL.Emit(OpCodes.Ldarg_0);
        ConstructorInfo? ci = typeof(object).GetConstructor(Type.EmptyTypes);
        ctor1IL.Emit(OpCodes.Call, ci!);
        // Push the instance on the stack before pushing the argument
        // that is to be assigned to the private field m_number.
        ctor1IL.Emit(OpCodes.Ldarg_0);
        ctor1IL.Emit(OpCodes.Ldarg_1);
        ctor1IL.Emit(OpCodes.Stfld, fbNumber);
        ctor1IL.Emit(OpCodes.Ret);

        // Define a default constructor that supplies a default value
        // for the private field. For parameter types, pass the empty
        // array of types or pass null.
        ConstructorBuilder ctor0 = tb.DefineConstructor(
            MethodAttributes.Public,
            CallingConventions.Standard,
            Type.EmptyTypes);

        ILGenerator ctor0IL = ctor0.GetILGenerator();
        // For a constructor, argument zero is a reference to the new
        // instance. Push it on the stack before pushing the default
        // value on the stack, then call constructor ctor1.
        ctor0IL.Emit(OpCodes.Ldarg_0);
        ctor0IL.Emit(OpCodes.Ldc_I4_S, 42);
        ctor0IL.Emit(OpCodes.Call, ctor1);
        ctor0IL.Emit(OpCodes.Ret);

        // Define a property named Number that gets and sets the private
        // field.
        //
        // The last argument of DefineProperty is null, because the
        // property has no parameters. (If you don't specify null, you must
        // specify an array of Type objects. For a parameterless property,
        // use the built-in array with no elements: Type.EmptyTypes)
        PropertyBuilder pbNumber = tb.DefineProperty(
            "Number",
            PropertyAttributes.HasDefault,
            typeof(int),
            null);

        // The property "set" and property "get" methods require a special
        // set of attributes.
        MethodAttributes getSetAttr = MethodAttributes.Public |
            MethodAttributes.SpecialName | MethodAttributes.HideBySig;

        // Define the "get" accessor method for Number. The method returns
        // an integer and has no arguments. (Note that null could be
        // used instead of Types.EmptyTypes)
        MethodBuilder mbNumberGetAccessor = tb.DefineMethod(
            "get_Number",
            getSetAttr,
            typeof(int),
            Type.EmptyTypes);

        ILGenerator numberGetIL = mbNumberGetAccessor.GetILGenerator();
        // For an instance property, argument zero is the instance. Load the
        // instance, then load the private field and return, leaving the
        // field value on the stack.
        numberGetIL.Emit(OpCodes.Ldarg_0);
        numberGetIL.Emit(OpCodes.Ldfld, fbNumber);
        numberGetIL.Emit(OpCodes.Ret);

        // Define the "set" accessor method for Number, which has no return
        // type and takes one argument of type int (Int32).
        MethodBuilder mbNumberSetAccessor = tb.DefineMethod(
            "set_Number",
            getSetAttr,
            null,
            new Type[] { typeof(int) });

        ILGenerator numberSetIL = mbNumberSetAccessor.GetILGenerator();
        // Load the instance and then the numeric argument, then store the
        // argument in the field.
        numberSetIL.Emit(OpCodes.Ldarg_0);
        numberSetIL.Emit(OpCodes.Ldarg_1);
        numberSetIL.Emit(OpCodes.Stfld, fbNumber);
        numberSetIL.Emit(OpCodes.Ret);

        // Last, map the "get" and "set" accessor methods to the
        // PropertyBuilder. The property is now complete.
        pbNumber.SetGetMethod(mbNumberGetAccessor);
        pbNumber.SetSetMethod(mbNumberSetAccessor);

        // Define a method that accepts an integer argument and returns
        // the product of that integer and the private field m_number. This
        // time, the array of parameter types is created on the fly.
        MethodBuilder meth = tb.DefineMethod(
            "MyMethod",
            MethodAttributes.Public,
            typeof(int),
            new Type[] { typeof(int) });

        ILGenerator methIL = meth.GetILGenerator();
        // To retrieve the private instance field, load the instance it
        // belongs to (argument zero). After loading the field, load the
        // argument one and then multiply. Return from the method with
        // the return value (the product of the two numbers) on the
        // execution stack.
        methIL.Emit(OpCodes.Ldarg_0);
        methIL.Emit(OpCodes.Ldfld, fbNumber);
        methIL.Emit(OpCodes.Ldarg_1);
        methIL.Emit(OpCodes.Mul);
        methIL.Emit(OpCodes.Ret);

        // Finish the type.
        Type? t = tb.CreateType();

        // Because AssemblyBuilderAccess includes Run, the code can be
        // executed immediately. Start by getting reflection objects for
        // the method and the property.
        MethodInfo? mi = t?.GetMethod("MyMethod");
        PropertyInfo? pi = t?.GetProperty("Number");

        // Create an instance of MyDynamicType using the default
        // constructor.
        object? o1 = null;
        if (t is not null)
            o1 = Activator.CreateInstance(t);

        // Display the value of the property, then change it to 127 and
        // display it again. Use null to indicate that the property
        // has no index.
        Console.WriteLine("o1.Number: {0}", pi?.GetValue(o1, null));
        pi?.SetValue(o1, 127, null);
        Console.WriteLine("o1.Number: {0}", pi?.GetValue(o1, null));

        // Call MyMethod, passing 22, and display the return value, 22
        // times 127. Arguments must be passed as an array, even when
        // there is only one.
        object[] arguments = { 22 };
        Console.WriteLine("o1.MyMethod(22): {0}",
            mi?.Invoke(o1, arguments));

        // Create an instance of MyDynamicType using the constructor
        // that specifies m_Number. The constructor is identified by
        // matching the types in the argument array. In this case,
        // the argument array is created on the fly. Display the
        // property value.
        object? o2 = null;
        if (t is not null)
            Activator.CreateInstance(t, new object[] { 5280 });
        Console.WriteLine("o2.Number: {0}", pi?.GetValue(o2, null));
    }
}

/* This code produces the following output:

o1.Number: 42
o1.Number: 127
o1.MyMethod(22): 2794
o2.Number: 5280
 */
open System
open System.Threading
open System.Reflection
open System.Reflection.Emit

// This code creates an assembly that contains one type,
// named "MyDynamicType", that has a private field, a property
// that gets and sets the private field, constructors that
// initialize the private field, and a method that multiplies
// a user-supplied number by the private field value and returns
// the result. In C# the type might look like this:
(*
public class MyDynamicType
{
    private int m_number;

    public MyDynamicType() : this(42) {}
    public MyDynamicType(int initNumber)
    {
        m_number = initNumber;
    }

    public int Number
    {
        get { return m_number; }
        set { m_number = value; }
    }

    public int MyMethod(int multiplier)
    {
        return m_number * multiplier;
    }
}
*)

let assemblyName = new AssemblyName("DynamicAssemblyExample")
let assemblyBuilder =
    AssemblyBuilder.DefineDynamicAssembly(
        assemblyName,
        AssemblyBuilderAccess.Run)

// The module name is usually the same as the assembly name.
let moduleBuilder =
    assemblyBuilder.DefineDynamicModule(assemblyName.Name)

let typeBuilder =
    moduleBuilder.DefineType(
        "MyDynamicType",
        TypeAttributes.Public)

// Add a private field of type int (Int32)
let fieldBuilderNumber =
    typeBuilder.DefineField(
        "m_number",
        typeof<int>,
        FieldAttributes.Private)

// Define a constructor1 that takes an integer argument and
// stores it in the private field.
let parameterTypes = [| typeof<int> |]
let ctor1 =
    typeBuilder.DefineConstructor(
        MethodAttributes.Public,
        CallingConventions.Standard,
        parameterTypes)

let ctor1IL = ctor1.GetILGenerator()

// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before calling the base
// class constructor. Specify the default constructor of the
// base class (System.Object) by passing an empty array of
// types (Type.EmptyTypes) to GetConstructor.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Call,
                 typeof<obj>.GetConstructor(Type.EmptyTypes))

// Push the instance on the stack before pushing the argument
// that is to be assigned to the private field m_number.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Ldarg_1)
ctor1IL.Emit(OpCodes.Stfld, fieldBuilderNumber)
ctor1IL.Emit(OpCodes.Ret)

// Define a default constructor1 that supplies a default value
// for the private field. For parameter types, pass the empty
// array of types or pass null.
let ctor0 =
    typeBuilder.DefineConstructor(
        MethodAttributes.Public,
        CallingConventions.Standard,
        Type.EmptyTypes)

let ctor0IL = ctor0.GetILGenerator()
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before pushing the default
// value on the stack, then call constructor ctor1.
ctor0IL.Emit(OpCodes.Ldarg_0)
ctor0IL.Emit(OpCodes.Ldc_I4_S, 42)
ctor0IL.Emit(OpCodes.Call, ctor1)
ctor0IL.Emit(OpCodes.Ret)

// Define a property named Number that gets and sets the private
// field.
//
// The last argument of DefineProperty is null, because the
// property has no parameters. (If you don't specify null, you must
// specify an array of Type objects. For a parameterless property,
// use the built-in array with no elements: Type.EmptyTypes)
let propertyBuilderNumber =
    typeBuilder.DefineProperty(
        "Number",
        PropertyAttributes.HasDefault,
        typeof<int>,
        null)

// The property "set" and property "get" methods require a special
// set of attributes.
let getSetAttr = MethodAttributes.Public ||| MethodAttributes.SpecialName ||| MethodAttributes.HideBySig

// Define the "get" accessor method for Number. The method returns
// an integer and has no arguments. (Note that null could be
// used instead of Types.EmptyTypes)
let methodBuilderNumberGetAccessor =
    typeBuilder.DefineMethod(
        "get_number",
        getSetAttr,
        typeof<int>,
        Type.EmptyTypes)

let numberGetIL =
    methodBuilderNumberGetAccessor.GetILGenerator()

// For an instance property, argument zero ir the instance. Load the
// instance, then load the private field and return, leaving the
// field value on the stack.
numberGetIL.Emit(OpCodes.Ldarg_0)
numberGetIL.Emit(OpCodes.Ldfld, fieldBuilderNumber)
numberGetIL.Emit(OpCodes.Ret)

// Define the "set" accessor method for Number, which has no return
// type and takes one argument of type int (Int32).
let methodBuilderNumberSetAccessor =
    typeBuilder.DefineMethod(
        "set_number",
        getSetAttr,
        null,
        [| typeof<int> |])

let numberSetIL =
    methodBuilderNumberSetAccessor.GetILGenerator()
// Load the instance and then the numeric argument, then store the
// argument in the field
numberSetIL.Emit(OpCodes.Ldarg_0)
numberSetIL.Emit(OpCodes.Ldarg_1)
numberSetIL.Emit(OpCodes.Stfld, fieldBuilderNumber)
numberSetIL.Emit(OpCodes.Ret)

// Last, map the "get" and "set" accessor methods to the
// PropertyBuilder. The property is now complete.
propertyBuilderNumber.SetGetMethod(methodBuilderNumberGetAccessor)
propertyBuilderNumber.SetSetMethod(methodBuilderNumberSetAccessor)

// Define a method that accepts an integer argument and returns
// the product of that integer and the private field m_number. This
// time, the array of parameter types is created on the fly.
let methodBuilder =
    typeBuilder.DefineMethod(
        "MyMethod",
        MethodAttributes.Public,
        typeof<int>,
        [| typeof<int> |])

let methodIL = methodBuilder.GetILGenerator()
// To retrieve the private instance field, load the instance it
// belongs to (argument zero). After loading the field, load the
// argument one and then multiply. Return from the method with
// the return value (the product of the two numbers) on the
// execution stack.
methodIL.Emit(OpCodes.Ldarg_0)
methodIL.Emit(OpCodes.Ldfld, fieldBuilderNumber)
methodIL.Emit(OpCodes.Ldarg_1)
methodIL.Emit(OpCodes.Mul)
methodIL.Emit(OpCodes.Ret)

// Finish the type
let typ = typeBuilder.CreateType()

// Because AssemblyBuilderAccess includes Run, the code can be
// executed immediately. Start by getting reflection objects for
// the method and the property.
let methodInfo = typ.GetMethod("MyMethod")
let propertyInfo = typ.GetProperty("Number")

// Create an instance of MyDynamicType using the default
// constructor.
let obj1 = Activator.CreateInstance(typ)

// Display the value of the property, then change it to 127 and
// display it again. Use null to indicate that the property
// has no index.
printfn "obj1.Number: %A" (propertyInfo.GetValue(obj1, null))
propertyInfo.SetValue(obj1, 127, null)
printfn "obj1.Number: %A" (propertyInfo.GetValue(obj1, null))

// Call MyMethod, pasing 22, and display the return value, 22
// times 127. Arguments must be passed as an array, even when
// there is only one.
let arguments: obj array = [| 22 |]
printfn "obj1.MyMethod(22): %A" (methodInfo.Invoke(obj1, arguments))

// Create an instance of MyDynamicType using the constructor
// that specifies m_Number. The constructor is identified by
// matching the types in the argument array. In this case,
// the argument array is created on the fly. Display the
// property value.
let constructorArguments: obj array = [| 5280 |]
let obj2 = Activator.CreateInstance(typ, constructorArguments)
printfn "obj2.Number: %A" (propertyInfo.GetValue(obj2, null))

(* This code produces the following output:

obj1.Number: 42
obj1.Number: 127
obj1.MyMethod(22): 2794
obj1.Number: 5280
*)
Imports System.Reflection
Imports System.Reflection.Emit

Class DemoAssemblyBuilder

    Public Shared Sub Main()

        ' This code creates an assembly that contains one type,
        ' named "MyDynamicType", that has a private field, a property
        ' that gets and sets the private field, constructors that
        ' initialize the private field, and a method that multiplies
        ' a user-supplied number by the private field value and returns
        ' the result. The code might look like this in Visual Basic:
        '
        'Public Class MyDynamicType
        '    Private m_number As Integer
        '
        '    Public Sub New()
        '        Me.New(42)
        '    End Sub
        '
        '    Public Sub New(ByVal initNumber As Integer)
        '        m_number = initNumber
        '    End Sub
        '
        '    Public Property Number As Integer
        '        Get
        '            Return m_number
        '        End Get
        '        Set
        '            m_Number = Value
        '        End Set
        '    End Property
        '
        '    Public Function MyMethod(ByVal multiplier As Integer) As Integer
        '        Return m_Number * multiplier
        '    End Function
        'End Class
      
        Dim aName As New AssemblyName("DynamicAssemblyExample")
        Dim ab As AssemblyBuilder = _
            AssemblyBuilder.DefineDynamicAssembly( _
                aName, _
                AssemblyBuilderAccess.Run)

        ' The module name is usually the same as the assembly name.
        Dim mb As ModuleBuilder = ab.DefineDynamicModule( _
            aName.Name)
      
        Dim tb As TypeBuilder = _
            mb.DefineType("MyDynamicType", TypeAttributes.Public)

        ' Add a private field of type Integer (Int32).
        Dim fbNumber As FieldBuilder = tb.DefineField( _
            "m_number", _
            GetType(Integer), _
            FieldAttributes.Private)

        ' Define a constructor that takes an integer argument and 
        ' stores it in the private field. 
        Dim parameterTypes() As Type = { GetType(Integer) }
        Dim ctor1 As ConstructorBuilder = _
            tb.DefineConstructor( _
                MethodAttributes.Public, _
                CallingConventions.Standard, _
                parameterTypes)

        Dim ctor1IL As ILGenerator = ctor1.GetILGenerator()
        ' For a constructor, argument zero is a reference to the new
        ' instance. Push it on the stack before calling the base
        ' class constructor. Specify the default constructor of the 
        ' base class (System.Object) by passing an empty array of 
        ' types (Type.EmptyTypes) to GetConstructor.
        ctor1IL.Emit(OpCodes.Ldarg_0)
        ctor1IL.Emit(OpCodes.Call, _
            GetType(Object).GetConstructor(Type.EmptyTypes))
        ' Push the instance on the stack before pushing the argument
        ' that is to be assigned to the private field m_number.
        ctor1IL.Emit(OpCodes.Ldarg_0)
        ctor1IL.Emit(OpCodes.Ldarg_1)
        ctor1IL.Emit(OpCodes.Stfld, fbNumber)
        ctor1IL.Emit(OpCodes.Ret)

        ' Define a default constructor that supplies a default value
        ' for the private field. For parameter types, pass the empty
        ' array of types or pass Nothing.
        Dim ctor0 As ConstructorBuilder = tb.DefineConstructor( _
            MethodAttributes.Public, _
            CallingConventions.Standard, _
            Type.EmptyTypes)

        Dim ctor0IL As ILGenerator = ctor0.GetILGenerator()
        ' For a constructor, argument zero is a reference to the new
        ' instance. Push it on the stack before pushing the default
        ' value on the stack, then call constructor ctor1.
        ctor0IL.Emit(OpCodes.Ldarg_0)
        ctor0IL.Emit(OpCodes.Ldc_I4_S, 42)
        ctor0IL.Emit(OpCodes.Call, ctor1)
        ctor0IL.Emit(OpCodes.Ret)

        ' Define a property named Number that gets and sets the private 
        ' field.
        '
        ' The last argument of DefineProperty is Nothing, because the
        ' property has no parameters. (If you don't specify Nothing, you must
        ' specify an array of Type objects. For a parameterless property,
        ' use the built-in array with no elements: Type.EmptyTypes)
        Dim pbNumber As PropertyBuilder = tb.DefineProperty( _
            "Number", _
            PropertyAttributes.HasDefault, _
            GetType(Integer), _
            Nothing)
      
        ' The property Set and property Get methods require a special
        ' set of attributes.
        Dim getSetAttr As MethodAttributes = _
            MethodAttributes.Public Or MethodAttributes.SpecialName _
                Or MethodAttributes.HideBySig

        ' Define the "get" accessor method for Number. The method returns
        ' an integer and has no arguments. (Note that Nothing could be 
        ' used instead of Types.EmptyTypes)
        Dim mbNumberGetAccessor As MethodBuilder = tb.DefineMethod( _
            "get_Number", _
            getSetAttr, _
            GetType(Integer), _
            Type.EmptyTypes)
      
        Dim numberGetIL As ILGenerator = mbNumberGetAccessor.GetILGenerator()
        ' For an instance property, argument zero is the instance. Load the 
        ' instance, then load the private field and return, leaving the
        ' field value on the stack.
        numberGetIL.Emit(OpCodes.Ldarg_0)
        numberGetIL.Emit(OpCodes.Ldfld, fbNumber)
        numberGetIL.Emit(OpCodes.Ret)
        
        ' Define the "set" accessor method for Number, which has no return
        ' type and takes one argument of type Integer (Int32).
        Dim mbNumberSetAccessor As MethodBuilder = _
            tb.DefineMethod( _
                "set_Number", _
                getSetAttr, _
                Nothing, _
                New Type() { GetType(Integer) })
      
        Dim numberSetIL As ILGenerator = mbNumberSetAccessor.GetILGenerator()
        ' Load the instance and then the numeric argument, then store the
        ' argument in the field.
        numberSetIL.Emit(OpCodes.Ldarg_0)
        numberSetIL.Emit(OpCodes.Ldarg_1)
        numberSetIL.Emit(OpCodes.Stfld, fbNumber)
        numberSetIL.Emit(OpCodes.Ret)
      
        ' Last, map the "get" and "set" accessor methods to the 
        ' PropertyBuilder. The property is now complete. 
        pbNumber.SetGetMethod(mbNumberGetAccessor)
        pbNumber.SetSetMethod(mbNumberSetAccessor)

        ' Define a method that accepts an integer argument and returns
        ' the product of that integer and the private field m_number. This
        ' time, the array of parameter types is created on the fly.
        Dim meth As MethodBuilder = tb.DefineMethod( _
            "MyMethod", _
            MethodAttributes.Public, _
            GetType(Integer), _
            New Type() { GetType(Integer) })

        Dim methIL As ILGenerator = meth.GetILGenerator()
        ' To retrieve the private instance field, load the instance it
        ' belongs to (argument zero). After loading the field, load the 
        ' argument one and then multiply. Return from the method with 
        ' the return value (the product of the two numbers) on the 
        ' execution stack.
        methIL.Emit(OpCodes.Ldarg_0)
        methIL.Emit(OpCodes.Ldfld, fbNumber)
        methIL.Emit(OpCodes.Ldarg_1)
        methIL.Emit(OpCodes.Mul)
        methIL.Emit(OpCodes.Ret)

        ' Finish the type.
        Dim t As Type = tb.CreateType()

        ' Because AssemblyBuilderAccess includes Run, the code can be
        ' executed immediately. Start by getting reflection objects for
        ' the method and the property.
        Dim mi As MethodInfo = t.GetMethod("MyMethod")
        Dim pi As PropertyInfo = t.GetProperty("Number")
  
        ' Create an instance of MyDynamicType using the default 
        ' constructor. 
        Dim o1 As Object = Activator.CreateInstance(t)

        ' Display the value of the property, then change it to 127 and 
        ' display it again. Use Nothing to indicate that the property
        ' has no index.
        Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, Nothing))
        pi.SetValue(o1, 127, Nothing)
        Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, Nothing))

        ' Call MyMethod, passing 22, and display the return value, 22
        ' times 127. Arguments must be passed as an array, even when
        ' there is only one.
        Dim arguments() As Object = { 22 }
        Console.WriteLine("o1.MyMethod(22): {0}", _
            mi.Invoke(o1, arguments))

        ' Create an instance of MyDynamicType using the constructor
        ' that specifies m_Number. The constructor is identified by
        ' matching the types in the argument array. In this case, 
        ' the argument array is created on the fly. Display the 
        ' property value.
        Dim o2 As Object = Activator.CreateInstance(t, _
            New Object() { 5280 })
        Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, Nothing))
      
    End Sub  
End Class

' This code produces the following output:
'
'o1.Number: 42
'o1.Number: 127
'o1.MyMethod(22): 2794
'o2.Number: 5280

Remarques

Pour plus d’informations sur cette API, consultez Remarques supplémentaires sur l’API pour AssemblyBuilder.

Constructeurs

AssemblyBuilder()

Initialise une nouvelle instance de la classe AssemblyBuilder.

Propriétés

CodeBase
Obsolète.

Obtient l’emplacement de l’assembly, telle que spécifié à l’origine (par exemple dans un objet AssemblyName).

CodeBase
Obsolète.
Obsolète.

Obtient l'emplacement de l'assembly tel qu'il a été spécifié à l'origine, par exemple dans un objet AssemblyName.

(Hérité de Assembly)
CustomAttributes

Obtient une collection qui contient les attributs personnalisés de cet assembly.

(Hérité de Assembly)
DefinedTypes

Définit et représente un assembly dynamique.

DefinedTypes

Obtient une collection des types définis dans cet assembly.

(Hérité de Assembly)
EntryPoint

Obtient le point d’entrée de cet assembly.

EntryPoint

Obtient le point d'entrée de cet assembly.

(Hérité de Assembly)
EscapedCodeBase
Obsolète.
Obsolète.

Obtient l'URI, y compris les caractères d'espacement, qui représente le code base.

(Hérité de Assembly)
Evidence

Obtient la preuve pour cet assembly.

Evidence

Obtient la preuve pour cet assembly.

(Hérité de Assembly)
ExportedTypes

Obtient une collection des types publics définis dans cet assembly qui sont visibles à l'extérieur de l'assembly.

(Hérité de Assembly)
FullName

Obtient le nom d’affichage de l’assembly dynamique actuel.

FullName

Obtient le nom complet de l'assembly.

(Hérité de Assembly)
GlobalAssemblyCache
Obsolète.

Obtient une valeur qui indique si l’assembly a été chargé à partir du Global Assembly Cache.

GlobalAssemblyCache
Obsolète.

Obtient une valeur indiquant si l’assembly a été chargé à partir du global assembly cache (.NET Framework uniquement).

(Hérité de Assembly)
HostContext

Obtient le contexte hôte où l’assembly dynamique est créé.

HostContext

Obtient le contexte hôte avec lequel l'assembly a été chargé.

(Hérité de Assembly)
ImageRuntimeVersion

Obtient la version du Common Language Runtime (CLR) qui sera enregistrée dans le fichier contenant le manifeste.

ImageRuntimeVersion

Obtient une représentation sous forme de chaîne de la version du Common Language Runtime (CLR) enregistrée dans le fichier contenant le manifeste.

(Hérité de Assembly)
IsCollectible

Obtient une valeur qui indique si cet assembly dynamique est conservé dans un objet de AssemblyLoadContextcollecte .

IsCollectible

Obtient une valeur qui indique si l’assembly est contenu dans un AssemblyLoadContext pouvant être collecté.

(Hérité de Assembly)
IsDynamic

Obtient une valeur qui indique que l’assembly actuel est un assembly dynamique.

IsDynamic

Obtient une valeur qui indique si l'assembly actuel a été généré dynamiquement dans le processus actuel à l'aide de l'émission de réflexion.

(Hérité de Assembly)
IsFullyTrusted

Obtient une valeur qui indique si l'assembly actuel est chargé avec une confiance totale.

(Hérité de Assembly)
Location

Obtient l’emplacement, au format code base, du fichier chargé qui contient le manifeste, s’il n’est pas un cliché instantané.

Location

Obtient le chemin d’accès complet ou l’emplacement UNC du fichier chargé qui contient le manifeste.

(Hérité de Assembly)
ManifestModule

Obtient le module du AssemblyBuilder actuel qui contient le manifeste de l’assembly.

ManifestModule

Obtient le module qui contient le manifeste de l'assembly actuel.

(Hérité de Assembly)
Modules

Définit et représente un assembly dynamique.

Modules

Obtient une collection qui contient les modules dans cet assembly.

(Hérité de Assembly)
PermissionSet

Obtient le jeu accordé de l’assembly dynamique actuel.

PermissionSet

Obtient le jeu accordé de l'assembly actuel.

(Hérité de Assembly)
ReflectionOnly

Obtient une valeur indiquant si l’assembly dynamique est dans le contexte de réflexion uniquement.

ReflectionOnly

Obtient une valeur Boolean indiquant si cet assembly a été chargé dans le contexte de réflexion uniquement.

(Hérité de Assembly)
SecurityRuleSet

Obtient une valeur qui indique quel ensemble de règles de sécurité le Common Language Runtime (CLR) applique pour cet assembly.

SecurityRuleSet

Obtient une valeur qui indique quel ensemble de règles de sécurité le Common Language Runtime (CLR) applique pour cet assembly.

(Hérité de Assembly)

Méthodes

AddResourceFile(String, String)

Ajoute un fichier de ressources existant à cet assembly.

AddResourceFile(String, String, ResourceAttributes)

Ajoute un fichier de ressources existant à cet assembly.

CreateInstance(String)

Recherche le type spécifié dans cet assembly et en crée une instance à l'aide de l'activateur système, avec une recherche respectant la casse.

(Hérité de Assembly)
CreateInstance(String, Boolean)

Recherche le type spécifié dans cet assembly et en crée une instance à l'aide de l'activateur système, avec une recherche facultative respectant la casse.

(Hérité de Assembly)
CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

Recherche le type spécifié dans cet assembly et en crée une instance à l'aide de l'activateur système, avec une recherche facultative respectant la casse et possédant la culture, les arguments, ainsi que les attributs de liaison et d'activation spécifiés.

(Hérité de Assembly)
DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)

Définit un assembly dynamique qui porte le nom spécifié et possède les droits d’accès spécifiés.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)

Définit un nouvel assembly avec le nom, les droits d’accès et les attributs spécifiés.

DefineDynamicModule(String)

Définit un module dynamique transitoire nommé dans cet assembly.

DefineDynamicModule(String, Boolean)

Définit un module dynamique transitoire nommé dans cet assembly et spécifie si des informations de symboles doivent être émises.

DefineDynamicModule(String, String)

Définit un module dynamique persistant avec le nom donné à enregistrer dans le fichier spécifié. Aucune information de symbole n’est émise.

DefineDynamicModule(String, String, Boolean)

Définit un module dynamique persistant, en spécifiant le nom du module, le nom du fichier dans lequel le module doit être enregistré et si les informations de symbole doivent être émises à l’aide du writer de symbole par défaut.

DefineDynamicModuleCore(String)

En cas de substitution dans une classe dérivée, définit un module dynamique dans cet assembly.

DefinePersistedAssembly(AssemblyName, Assembly, IEnumerable<CustomAttributeBuilder>)

Définit et représente un assembly dynamique.

DefineResource(String, String, String)

Définit une ressource managée autonome pour cet assembly avec l’attribut de ressource public par défaut.

DefineResource(String, String, String, ResourceAttributes)

Définit une ressource managée autonome pour cet assembly. Des attributs peuvent être spécifiés pour la ressource managée.

DefineUnmanagedResource(Byte[])

Définit une ressource non managée pour cet assembly en tant qu’objet blob d’octets opaque.

DefineUnmanagedResource(String)

Définit un fichier de ressources non managées pour cet assembly selon le nom du fichier de ressources.

DefineVersionInfoResource()

Définit une ressource d’informations de version non managée en utilisant les informations spécifiées dans l’objet AssemblyName de l’assembly et les attributs personnalisés de l’assembly.

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

Définit une ressource d’informations de version non managée pour cet assembly avec les spécifications données.

Equals(Object)

Retourne une valeur qui indique si cette instance est égale à l’objet spécifié.

Equals(Object)

Détermine si cet assembly et l'objet spécifié sont égaux.

(Hérité de Assembly)
GetCustomAttributes(Boolean)

Retourne tous les attributs personnalisés qui ont été appliqués au AssemblyBuilder actuel.

GetCustomAttributes(Boolean)

Obtient tous les attributs personnalisés pour cet assembly.

(Hérité de Assembly)
GetCustomAttributes(Type, Boolean)

Retourne tous les attributs personnalisés qui ont été appliqués à l’élément AssemblyBuilder actuel et qui dérivent d’un type d’attribut spécifié.

GetCustomAttributes(Type, Boolean)

Obtient les attributs personnalisés pour cet assembly, tels qu'ils sont spécifiés par le type.

(Hérité de Assembly)
GetCustomAttributesData()

Retourne des objets CustomAttributeData qui contiennent des informations sur les attributs qui ont été appliqués au AssemblyBuilder actuel.

GetCustomAttributesData()

Retourne des informations sur les attributs appliqués au Assembly actuel, en tant qu'objets CustomAttributeData.

(Hérité de Assembly)
GetDynamicModule(String)

Retourne le module dynamique avec le nom spécifié.

GetDynamicModuleCore(String)

En cas de substitution dans une classe dérivée, retourne le module dynamique avec le nom spécifié.

GetExportedTypes()

Obtient les types exportés définis dans cet assembly.

GetExportedTypes()

Obtient les types publics définis dans cet assembly qui sont visibles à l'extérieur de l'assembly.

(Hérité de Assembly)
GetFile(String)

Obtient un FileStream pour le fichier spécifié dans la table de fichiers du manifeste de cet assembly.

GetFile(String)

Obtient un FileStream pour le fichier spécifié dans la table de fichiers du manifeste de cet assembly.

(Hérité de Assembly)
GetFiles()

Obtient les fichiers de la table de fichiers d'un manifeste d'assembly.

(Hérité de Assembly)
GetFiles(Boolean)

Obtient les fichiers de la table de fichiers d'un manifeste d'assembly, en spécifiant si des modules de ressources doivent être inclus.

GetFiles(Boolean)

Obtient les fichiers de la table de fichiers d'un manifeste d'assembly, en spécifiant si des modules de ressources doivent être inclus.

(Hérité de Assembly)
GetForwardedTypes()

Définit et représente un assembly dynamique.

(Hérité de Assembly)
GetHashCode()

Retourne le code de hachage de cette instance.

GetHashCode()

Retourne le code de hachage de cette instance.

(Hérité de Assembly)
GetLoadedModules()

Obtient tous les modules chargés qui appartiennent à cet assembly.

(Hérité de Assembly)
GetLoadedModules(Boolean)

Retourne tous les modules chargés qui appartiennent à cet assembly et inclut éventuellement des modules de ressources.

GetLoadedModules(Boolean)

Obtient tous les modules chargés qui appartiennent à cet assembly, en spécifiant si des modules de ressources doivent être inclus.

(Hérité de Assembly)
GetManifestResourceInfo(String)

Retourne des informations sur la manière dont la ressource donnée a été persistante.

GetManifestResourceNames()

Charge la ressource de manifeste spécifiée à partir de cet assembly.

GetManifestResourceStream(String)

Charge la ressource de manifeste spécifiée à partir de cet assembly.

GetManifestResourceStream(Type, String)

Charge la ressource de manifeste spécifiée, dont la portée est définie par l'espace de noms du type déterminé, à partir de cet assembly.

GetManifestResourceStream(Type, String)

Charge la ressource de manifeste spécifiée, dont la portée est définie par l'espace de noms du type déterminé, à partir de cet assembly.

(Hérité de Assembly)
GetModule(String)

Obtient le module spécifié dans cet assembly.

GetModule(String)

Obtient le module spécifié dans cet assembly.

(Hérité de Assembly)
GetModules()

Obtient tous les modules qui appartiennent à cet assembly.

(Hérité de Assembly)
GetModules(Boolean)

Obtient tous les modules qui appartiennent à cet assembly et inclut éventuellement des modules de ressources.

GetModules(Boolean)

Obtient tous les modules qui appartiennent à cet assembly, en spécifiant si des modules de ressources doivent être inclus.

(Hérité de Assembly)
GetName()

Obtient AssemblyName pour cet assembly.

(Hérité de Assembly)
GetName(Boolean)

Obtient le AssemblyName qui a été spécifié quand l’assembly dynamique actuel a été créé, et définit la base code comme spécifié.

GetName(Boolean)

Obtient un AssemblyName pour cet assembly, en définissant le code base de la manière spécifiée par copiedName.

(Hérité de Assembly)
GetObjectData(SerializationInfo, StreamingContext)
Obsolète.

Obtient les informations de sérialisation avec toutes les données nécessaires pour réinstancier cet assembly.

(Hérité de Assembly)
GetReferencedAssemblies()

Obtient une liste incomplète d’objets AssemblyName pour les assemblys référencés par ce AssemblyBuilder.

GetReferencedAssemblies()

Obtient les objets AssemblyName pour tous les assemblys référencés par cet assembly.

(Hérité de Assembly)
GetSatelliteAssembly(CultureInfo)

Obtient l'assembly satellite pour la culture spécifiée.

GetSatelliteAssembly(CultureInfo)

Obtient l'assembly satellite pour la culture spécifiée.

(Hérité de Assembly)
GetSatelliteAssembly(CultureInfo, Version)

Obtient la version spécifiée de l'assembly satellite pour la culture donnée.

GetSatelliteAssembly(CultureInfo, Version)

Obtient la version spécifiée de l'assembly satellite pour la culture donnée.

(Hérité de Assembly)
GetType()

Définit et représente un assembly dynamique.

(Hérité de Assembly)
GetType(String)

Obtient l'objet Type avec le nom spécifié dans l'instance de l'assembly.

(Hérité de Assembly)
GetType(String, Boolean)

Obtient l'objet Type portant le nom spécifié dans l'instance de l'assembly et lève éventuellement une exception si le type est introuvable.

(Hérité de Assembly)
GetType(String, Boolean, Boolean)

Obtient le type spécifié parmi les types définis et créés dans le AssemblyBuilder actuel.

GetType(String, Boolean, Boolean)

Obtient l'objet Type portant le nom spécifié dans l'instance de l'assembly et propose d'ignorer la casse et de lever une exception si le type est introuvable.

(Hérité de Assembly)
GetTypes()

Obtient tous les types définis dans cet assembly.

(Hérité de Assembly)
IsDefined(Type, Boolean)

Retourne une valeur qui indique si une ou plusieurs instances du type d’attribut spécifié sont appliquées à ce membre.

IsDefined(Type, Boolean)

Indique si un attribut spécifié a été appliqué à l'assembly ou non.

(Hérité de Assembly)
LoadModule(String, Byte[])

Charge le module, interne à cet assembly, avec une image COFF (Common Object File Format) contenant un module émis ou un fichier de ressources.

(Hérité de Assembly)
LoadModule(String, Byte[], Byte[])

Charge le module, interne à cet assembly, avec une image COFF (Common Object File Format) contenant un module émis ou un fichier de ressources. Les octets bruts représentant les symboles du module sont également chargés.

(Hérité de Assembly)
MemberwiseClone()

Crée une copie superficielle du Object actuel.

(Hérité de Object)
Save(Stream)

Définit et représente un assembly dynamique.

Save(String)

Enregistre cet assembly dynamique sur le disque.

Save(String, PortableExecutableKinds, ImageFileMachine)

Enregistre cet assembly dynamique sur le disque, en spécifiant la nature du code contenu dans les fichiers exécutables de l’assembly, ainsi que la plateforme cible.

SaveCore(Stream)

Définit et représente un assembly dynamique.

SetCustomAttribute(ConstructorInfo, Byte[])

Définit un attribut personnalisé sur cet assembly à l’aide d’un objet blob d’attribut personnalisé spécifié.

SetCustomAttribute(CustomAttributeBuilder)

Définissez un attribut personnalisé sur cet assembly à l’aide d’un générateur d’attributs personnalisés.

SetCustomAttributeCore(ConstructorInfo, ReadOnlySpan<Byte>)

En cas de substitution dans une classe dérivée, définit un attribut personnalisé sur cet assembly.

SetEntryPoint(MethodInfo)

Définit le point d’entrée de cet assembly dynamique, en supposant que l’application créée est une application console.

SetEntryPoint(MethodInfo, PEFileKinds)

Définit le point d’entrée pour cet assembly et le type du fichier exécutable portable (fichier PE) en cours de génération.

ToString()

Retourne le nom complet de l'assembly.

(Hérité de Assembly)

Événements

ModuleResolve

Se produit si le chargeur de classes du Common Language Runtime ne peut pas résoudre une référence à un module interne d'un assembly à l'aide des moyens normaux.

(Hérité de Assembly)

Implémentations d’interfaces explicites

_Assembly.GetType()

Retourne le type de l'instance actuelle.

(Hérité de Assembly)
_AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mappe un jeu de noms avec un jeu correspondant d'identificateurs de dispatch.

_AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr)

Récupère les informations de type pour un objet, qui peuvent être utilisées ensuite pour obtenir les informations de type d'une interface.

_AssemblyBuilder.GetTypeInfoCount(UInt32)

Récupère le nombre d'interfaces d'informations de type fourni par un objet (0 ou 1).

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

Fournit l'accès aux propriétés et aux méthodes exposées par un objet.

ICustomAttributeProvider.GetCustomAttributes(Boolean)

Retourne un tableau de tous les attributs personnalisés définis sur ce membre, en dehors des attributs nommés, ou un tableau vide s’il n’y a aucun attribut personnalisé.

(Hérité de Assembly)
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean)

Retourne un tableau d’attributs personnalisés définis sur ce membre, identifiés par type, ou un tableau vide s’il n’y a aucun attribut personnalisé de ce type.

(Hérité de Assembly)
ICustomAttributeProvider.IsDefined(Type, Boolean)

Indique si une ou plusieurs instances de attributeType sont définies sur ce membre.

(Hérité de Assembly)

Méthodes d’extension

GetExportedTypes(Assembly)

Définit et représente un assembly dynamique.

GetModules(Assembly)

Définit et représente un assembly dynamique.

GetTypes(Assembly)

Définit et représente un assembly dynamique.

GetCustomAttribute(Assembly, Type)

Récupère un attribut personnalisé d'un type spécifié qui est appliqué à un assembly spécifié.

GetCustomAttribute<T>(Assembly)

Récupère un attribut personnalisé d'un type spécifié qui est appliqué à un assembly spécifié.

GetCustomAttributes(Assembly)

Récupère une collection d'attributs personnalisés qui sont appliqués à un assembly spécifié.

GetCustomAttributes(Assembly, Type)

Extrait une collection d'attributs personnalisés d'un type spécifié qui sont appliqués à un assembly spécifié.

GetCustomAttributes<T>(Assembly)

Extrait une collection d'attributs personnalisés d'un type spécifié qui sont appliqués à un assembly spécifié.

IsDefined(Assembly, Type)

Indique si des attributs personnalisés d'un type spécifié sont appliqués à un assembly spécifié.

TryGetRawMetadata(Assembly, Byte*, Int32)

Récupère la section de métadonnées de l’assembly, à utiliser avec MetadataReader.

S’applique à

Voir aussi