AssemblyBuilder AssemblyBuilder AssemblyBuilder AssemblyBuilder Class

定义

定义并表示动态程序集。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
继承
AssemblyBuilderAssemblyBuilderAssemblyBuilderAssemblyBuilder
属性
实现

示例

下面的代码示例演示如何定义具有一个模块的动态程序集。The following code example shows how to define a dynamic assembly with one module. 该示例程序集中模块包含一个类型, MyDynamicType,其中具有私有字段、 获取和设置私有字段的属性、 构造函数初始化的私有字段和乘以用户提供的数字的私有字段的方法值并返回结果。The module in the example assembly contains one type, MyDynamicType, which has a private field, a property that gets and sets the private field, constructors that initialize the private field, and a method that multiplies a user-supplied number by the private field value and returns the result.

AssemblyBuilderAccess.RunAndSave 指定当创建该程序集。AssemblyBuilderAccess.RunAndSave is specified when the assembly is created. 立即使用的程序集代码和程序集也会保存到磁盘,以便它可以使用检查Ildasm.exe (IL 反汇编程序)或其他程序中使用。The assembly code is used immediately, and the assembly is also saved to disk so that it can be examined with Ildasm.exe (IL Disassembler) or used in another program.

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

void main()
{
    // An assembly consists of one or more modules, each of which
    // contains zero or more types. This code creates a single-module
    // assembly, the most common case. The module contains one type,
    // named "MyDynamicType", that has a private field, a property 
    // that gets and sets the private field, constructors that 
    // initialize the private field, and a method that multiplies 
    // a user-supplied number by the private field value and returns
    // the result. In Visual C++ the type might look like this:
    /*
      public ref class MyDynamicType
      {
      private:
          int m_number;

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

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

    // For a single-module assembly, the module name is usually
    // the assembly name plus an extension.
    ModuleBuilder^ mb = 
        ab->DefineDynamicModule(aName->Name, aName->Name + ".dll");
      
    TypeBuilder^ tb = mb->DefineType(
        "MyDynamicType", 
         TypeAttributes::Public);

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

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

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

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

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

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

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

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

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

    // Finish the type->
    Type^ t = tb->CreateType();
     
    // The following line saves the single-module assembly. This
    // requires AssemblyBuilderAccess to include Save. You can now
    // type "ildasm MyDynamicAsm.dll" at the command prompt, and 
    // examine the assembly. You can also write a program that has
    // a reference to the assembly, and use the MyDynamicType type.
    // 
    ab->Save(aName->Name + ".dll");

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

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

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

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

/* This code produces the following output:

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

class DemoAssemblyBuilder
{
    public static void Main()
    {
        // An assembly consists of one or more modules, each of which
        // contains zero or more types. This code creates a single-module
        // assembly, the most common case. The module contains one type,
        // named "MyDynamicType", that has a private field, a property 
        // that gets and sets the private field, constructors that 
        // initialize the private field, and a method that multiplies 
        // a user-supplied number by the private field value and returns
        // the result. In C# the type might look like this:
        /*
        public class MyDynamicType
        {
            private int m_number;
        
            public MyDynamicType() : this(42) {}
            public MyDynamicType(int initNumber)
            {
                m_number = initNumber;
            }

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

            public int MyMethod(int multiplier)
            {
                return m_number * multiplier;
            }
        }
        */
      
        AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
        AssemblyBuilder ab = 
            AppDomain.CurrentDomain.DefineDynamicAssembly(
                aName, 
                AssemblyBuilderAccess.RunAndSave);

        // For a single-module assembly, the module name is usually
        // the assembly name plus an extension.
        ModuleBuilder mb = 
            ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
      
        TypeBuilder tb = mb.DefineType(
            "MyDynamicType", 
             TypeAttributes.Public);

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

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

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

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

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

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

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

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

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

        // Finish the type.
        Type t = tb.CreateType();
     
        // The following line saves the single-module assembly. This
        // requires AssemblyBuilderAccess to include Save. You can now
        // type "ildasm MyDynamicAsm.dll" at the command prompt, and 
        // examine the assembly. You can also write a program that has
        // a reference to the assembly, and use the MyDynamicType type.
        // 
        ab.Save(aName.Name + ".dll");

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

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

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

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

/* This code produces the following output:

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

Class DemoAssemblyBuilder

    Public Shared Sub Main()

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

        ' For a single-module assembly, the module name is usually
        ' the assembly name plus an extension.
        Dim mb As ModuleBuilder = ab.DefineDynamicModule( _
            aName.Name, _
            aName.Name & ".dll")
      
        Dim tb As TypeBuilder = _
            mb.DefineType("MyDynamicType", TypeAttributes.Public)

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

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

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

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

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

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

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

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

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

        ' Finish the type.
        Dim t As Type = tb.CreateType()
     
        ' The following line saves the single-module assembly. This
        ' requires AssemblyBuilderAccess to include Save. You can now
        ' type "ildasm MyDynamicAsm.dll" at the command prompt, and 
        ' examine the assembly. You can also write a program that has
        ' a reference to the assembly, and use the MyDynamicType type.
        ' 
        ab.Save(aName.Name & ".dll") 

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

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

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

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

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

注解

动态程序集是使用反射发出 Api 创建一个程序集。A dynamic assembly is an assembly that is created using the Reflection Emit APIs. 使用保存动态程序集时,将保存在程序集中的动态模块Save方法。The dynamic modules in the assembly are saved when the dynamic assembly is saved using the Save method. 若要生成可执行文件,SetEntryPoint必须调用方法来标识将是对程序集的入口点的方法。To generate an executable, the SetEntryPoint method must be called to identify the method that is the entry point to the assembly. 程序集保存为 Dll 默认情况下,除非SetEntryPoint方法请求生成一个控制台应用程序或基于 Windows 的应用程序。Assemblies are saved as DLLs by default, unless the SetEntryPoint method requests the generation of a console application or a Windows-based application.

如果动态程序集包含多个动态模块,该程序集的清单文件名称应与指定为第一个参数的模块的名称DefineDynamicModule方法。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.

基上的某些方法Assembly类,如GetModulesGetLoadedModules,将无法正常工作时从调用AssemblyBuilder对象。Some methods on the base Assembly class, such as GetModules and GetLoadedModules, will not work correctly when called from AssemblyBuilder objects. 可以加载定义动态程序集,并针对加载的程序集调用的方法。You can load the defined dynamic assembly and call the methods on the loaded assembly. 例如,若要确保资源模块都包含在返回的模块列表中,调用GetModules对加载Assembly对象。For example, to ensure that resource modules are included in the returned module list, call GetModules on the loaded Assembly object.

动态程序集使用的签名KeyPair才会生效的程序集保存到磁盘。The signing of a dynamic assembly using KeyPair is not effective until the assembly is saved to disk. 因此,强名称不会使用瞬态动态程序集。So, strong names will not work with transient dynamic assemblies.

若要获取AssemblyBuilder对象,请使用AppDomain.DefineDynamicAssembly方法。To get an AssemblyBuilder object, use the AppDomain.DefineDynamicAssembly method.

反射发出动态程序集应用场景Reflection emit dynamic assembly scenarios

以下是一些需要时使用,请考虑事项AssemblyBuilder类,以创建动态程序集。The following are some things to consider when using the AssemblyBuilder class to create dynamic assemblies.

动态模块Dynamic modules

反射发出支持创建动态程序集中定义的动态模块。Reflection emit supports the creation of dynamic modules defined in dynamic assemblies. 在动态程序集中创建的动态模块可以是临时或持久性。A dynamic module created in a dynamic assembly can be transient or persistable.

类型引用的限制Restrictions on type references

程序集可以引用另一个程序集中定义的类型。Assemblies can reference types defined in another assembly. 瞬态动态程序集可以安全地引用中另一个瞬态动态程序集、 持久的动态程序集或静态程序集定义的类型。A transient dynamic assembly can safely reference types defined in another transient dynamic assembly, a persistable dynamic assembly, or a static assembly. 但是,公共语言运行时不允许持久动态模块,以引用瞬态动态模块中定义的类型。However, the common language runtime does not allow a persistable dynamic module to reference a type defined in a transient dynamic module. 这是因为当将持久动态模块加载时保存到磁盘,在运行时无法解析对瞬态动态模块中定义的类型的引用。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.

向远程应用程序域发送元组的限制Restrictions on emitting to remote application domains

某些情况下需要创建和执行远程应用程序域中的动态程序集。Some scenarios require a dynamic assembly to be created and executed in a remote application domain. 反射发出不允许直接到远程应用程序域发出动态程序集。Reflection emit does not allow a dynamic assembly to be emitted directly to a remote application domain. 解决方案是发出动态程序集在当前应用程序域中的,将发出动态程序集保存到磁盘,然后将动态程序集加载到远程应用程序域。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.

动态程序集访问模式Dynamic assembly access modes

可以使用以下访问模式之一来创建动态程序集:Dynamic assemblies can be created using one of the following access modes:

  • AssemblyBuilderAccess.Run

    表示动态程序集AssemblyBuilder是暂时性的对象。The dynamic assembly represented by an AssemblyBuilder object is transient. 动态程序集仅可用于执行发出的代码。The dynamic assembly can only be used to execute the emitted code.

  • AssemblyBuilderAccess.Save

    表示动态程序集AssemblyBuilder对象是持久的但之前已从磁盘加载已保存的可移植可执行 (PE) 文件,无法执行。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

    表示动态程序集AssemblyBuilder对象是持久的但之前/之后保存程序集或也可以执行到磁盘。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.

必须提供相应指定访问模式AssemblyBuilderAccess值对的调用中AssemblyBuilder.DefineDynamicAssembly方法时动态程序集定义,并且以后无法更改。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. 运行时使用动态程序集的访问的模式以优化程序集的内部表示形式。The runtime uses the access mode of a dynamic assembly to optimize the assembly's internal representation.

构造函数

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

属性

CodeBase CodeBase CodeBase CodeBase

获取最初指定的程序集的位置(例如,在 AssemblyName 对象中)。Gets the location of the assembly, as specified originally (such as in an AssemblyName object).

CustomAttributes CustomAttributes CustomAttributes CustomAttributes

获取包含此程序集自定义属性的集合。Gets a collection that contains this assembly's custom attributes.

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

返回此程序集的入口点。Returns the entry point of this assembly.

EscapedCodeBase EscapedCodeBase EscapedCodeBase EscapedCodeBase

获取 URI,包括表示基本代码的转义符。Gets the URI, including escape characters, that represents the codebase.

(Inherited from Assembly)
Evidence Evidence Evidence Evidence

获取此程序集的证据。Gets the evidence for this assembly.

ExportedTypes ExportedTypes ExportedTypes ExportedTypes

获取此程序集中定义的公共类型的集合,这些公共类型在程序集外可见。Gets a collection of the public types defined in this assembly that are visible outside the assembly.

(Inherited from Assembly)
FullName FullName FullName FullName

获取当前动态程序集的显示名称。Gets the display name of the current dynamic assembly.

GlobalAssemblyCache GlobalAssemblyCache GlobalAssemblyCache GlobalAssemblyCache

获取一个值,该值指示程序集是否是从全局程序集缓存加载的。Gets a value that indicates whether the assembly was loaded from the global assembly cache.

HostContext HostContext HostContext HostContext

获取创建动态程序集的主机上下文。Gets the host context where the dynamic assembly is being created.

ImageRuntimeVersion ImageRuntimeVersion ImageRuntimeVersion ImageRuntimeVersion

获取将在包含清单的文件中保存的公共语言运行时的版本。Gets the version of the common language runtime that will be saved in the file containing the manifest.

IsCollectible IsCollectible IsCollectible IsCollectible

获取一个值,该值指示此程序集是否保留在可回收的 AssemblyLoadContext 中。Gets a value that indicates whether this assembly is held in a collectible AssemblyLoadContext.

(Inherited from Assembly)
IsDynamic IsDynamic IsDynamic IsDynamic

获取一个值,该值指示当前程序集是动态程序集。Gets a value that indicates that the current assembly is a dynamic assembly.

IsFullyTrusted IsFullyTrusted IsFullyTrusted IsFullyTrusted

获取一个值,该值指示当前程序集是否是以完全信任方式加载的。Gets a value that indicates whether the current assembly is loaded with full trust.

(Inherited from Assembly)
Location Location Location Location

如果包含清单的已加载文件未被影像复制,获取该文件的位置(基本代码的格式)。Gets the location, in codebase format, of the loaded file that contains the manifest if it is not shadow-copied.

ManifestModule ManifestModule ManifestModule ManifestModule

获取包含程序集清单的当前 AssemblyBuilder 中的模块。Gets the module in the current AssemblyBuilder that contains the assembly manifest.

Modules Modules Modules Modules
PermissionSet PermissionSet PermissionSet PermissionSet

获取当前动态程序集的授予集。Gets the grant set of the current dynamic assembly.

ReflectionOnly ReflectionOnly ReflectionOnly ReflectionOnly

获取一个值,该值指示动态程序集是否位于仅反射的上下文中。Gets a value indicating whether the dynamic assembly is in the reflection-only context.

SecurityRuleSet SecurityRuleSet SecurityRuleSet SecurityRuleSet

获取一个值,该值指示公共语言运行时 (CLR) 对此程序集强制执行的安全规则集。Gets a value that indicates which set of security rules the common language runtime (CLR) enforces for this assembly.

方法

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

将现有资源文件添加到此程序集。Adds an existing resource file to this assembly.

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

将现有资源文件添加到此程序集。Adds an existing resource file to this assembly.

CreateInstance(String) CreateInstance(String) CreateInstance(String) CreateInstance(String)

使用区分大小写的搜索,从此程序集中查找指定的类型,然后使用系统激活器创建它的实例。Locates the specified type from this assembly and creates an instance of it using the system activator, using case-sensitive search.

(Inherited from Assembly)
CreateInstance(String, Boolean) CreateInstance(String, Boolean) CreateInstance(String, Boolean) CreateInstance(String, Boolean)

使用可选的区分大小写搜索,从此程序集中查找指定的类型,然后使用系统激活器创建它的实例。Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search.

(Inherited from Assembly)
CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

使用可选的区分大小写搜索并具有指定的区域性、参数和绑定及激活特性,从此程序集中查找指定的类型,并使用系统激活器创建它的实例。Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search and having the specified culture, arguments, and binding and activation attributes.

(Inherited from Assembly)
DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)

定义一个动态程序集,该动态程序集具有指定的名称和访问权限。Defines a dynamic assembly that has the specified name and access rights.

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

使用指定的名称、访问模式和自定义特性定义动态程序集。Defines a new assembly that has the specified name, access rights, and attributes.

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

在此程序集中定义命名的瞬态动态模块。Defines a named transient dynamic module in this assembly.

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

在此程序集中定义命名的瞬态动态模块,并指定是否发出符号信息。Defines a named transient dynamic module in this assembly and specifies whether symbol information should be emitted.

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

用给定名称定义将保存到指定文件的持久动态模块。Defines a persistable dynamic module with the given name that will be saved to the specified file. 不发出符号信息。No symbol information is emitted.

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

定义持久动态模块,并指定模块名称、用于保存模块的文件名,同时指定是否使用默认符号编写器发出符号信息。Defines a persistable dynamic module, specifying the module name, the name of the file to which the module will be saved, and whether symbol information should be emitted using the default symbol writer.

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

用默认的公共资源特性为此程序集定义独立托管资源。Defines a standalone managed resource for this assembly with the default public resource attribute.

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

为此程序集定义独立托管资源。Defines a standalone managed resource for this assembly. 可为托管资源指定特性。Attributes can be specified for the managed resource.

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

将此程序集的非托管资源定义为不透明的字节 Blob。Defines an unmanaged resource for this assembly as an opaque blob of bytes.

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

已知资源文件名,定义此程序集的非托管资源文件。Defines an unmanaged resource file for this assembly given the name of the resource file.

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

使用程序集的 AssemblyName 对象和程序集的自定义特性中指定的信息,定义非托管版本信息资源。Defines an unmanaged version information resource using the information specified in the assembly's AssemblyName object and the assembly's custom attributes.

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

用给定的规范定义此程序集的非托管版本信息资源。Defines an unmanaged version information resource for this assembly with the given specifications.

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

返回一个值,该值指示此实例是否与指定的对象相等。Returns a value that indicates whether this instance is equal to the specified object.

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

返回已应用于当前 AssemblyBuilder 的所有自定义属性。Returns all the custom attributes that have been applied to the current AssemblyBuilder.

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

返回已应用于当前 AssemblyBuilder 且派生自指定特性类型的所有自定义特性。Returns all the custom attributes that have been applied to the current AssemblyBuilder, and that derive from a specified attribute type.

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

返回 CustomAttributeData 对象,这些对象包含已应用到当前 AssemblyBuilder 的特性的相关信息。Returns CustomAttributeData objects that contain information about the attributes that have been applied to the current AssemblyBuilder.

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

返回具有指定名称的动态模块。Returns the dynamic module with the specified name.

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

获取在此程序集中定义的导出类型。Gets the exported types defined in this assembly.

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

获取此程序集清单的文件表中指定文件的 FileStreamGets a FileStream for the specified file in the file table of the manifest of this assembly.

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

获取程序集清单文件表中的文件。Gets the files in the file table of an assembly manifest.

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

获取程序集清单的文件表中的文件,指定是否包括资源模块。Gets the files in the file table of an assembly manifest, specifying whether to include resource modules.

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

返回此实例的哈希代码。Returns the hash code for this instance.

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

获取作为此程序集的一部分的所有加载模块。Gets all the loaded modules that are part of this assembly.

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

返回属于此程序集的所有已加载模块,还可以包括资源模块。Returns all the loaded modules that are part of this assembly, and optionally includes resource modules.

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

返回关于给定资源如何保持的信息。Returns information about how the given resource has been persisted.

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

从此程序集加载指定的清单资源。Loads the specified manifest resource from this assembly.

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

从此程序集加载指定的清单资源。Loads the specified manifest resource from this assembly.

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

从此程序集加载指定清单资源,清单资源的范围由指定类型的命名空间确定。Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly.

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

获取此程序集中的指定模块。Gets the specified module in this assembly.

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

获取作为此程序集的一部分的所有模块。Gets all the modules that are part of this assembly.

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

获取属于此程序集的所有模块,还可以包括资源模块。Gets all the modules that are part of this assembly, and optionally includes resource modules.

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

获取此程序集的 AssemblyNameGets an AssemblyName for this assembly.

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

获取在创建当前动态程序集时指定的 AssemblyName,并将基本代码设置为指定代码。Gets the AssemblyName that was specified when the current dynamic assembly was created, and sets the code base as specified.

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

获取序列化信息,其中包含重新实例化此程序集所需的所有数据。Gets serialization information with all of the data needed to reinstantiate this assembly.

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

获取由此 AssemblyBuilder 引用的程序集的 AssemblyName 对象的不完整列表。Gets an incomplete list of AssemblyName objects for the assemblies that are referenced by this AssemblyBuilder.

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

获取指定区域性的附属程序集。Gets the satellite assembly for the specified culture.

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

获取指定区域性的附属程序集的指定版本。Gets the specified version of the satellite assembly for the specified culture.

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

获取程序集实例中具有指定名称的 Type 对象。Gets the Type object with the specified name in the assembly instance.

(Inherited from Assembly)
GetType(String, Boolean) GetType(String, Boolean) GetType(String, Boolean) GetType(String, Boolean)

获取程序集实例中具有指定名称的 Type 对象,并选择在找不到该类型时引发异常。Gets the Type object with the specified name in the assembly instance and optionally throws an exception if the type is not found.

(Inherited from Assembly)
GetType(String, Boolean, Boolean) GetType(String, Boolean, Boolean) GetType(String, Boolean, Boolean) GetType(String, Boolean, Boolean)

从已在当前 AssemblyBuilder 中定义并创建的类型中获取指定的类型。Gets the specified type from the types that have been defined and created in the current AssemblyBuilder.

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

获取此程序集中定义的类型。Gets the types defined in this assembly.

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

返回一个值,该值指示是否将指定特性类型的一个或多个实例应用于此成员。Returns a value that indicates whether one or more instances of the specified attribute type is applied to this member.

LoadModule(String, Byte[]) LoadModule(String, Byte[]) LoadModule(String, Byte[]) LoadModule(String, Byte[])

加载带有基于通用对象文件格式 (COFF) 的映像(包含已发出的模块)或资源文件的模块(该模块相对于此程序集是内部的)。Loads the module, internal to this assembly, with a common object file format (COFF)-based image containing an emitted module, or a resource file.

(Inherited from Assembly)
LoadModule(String, Byte[], Byte[]) LoadModule(String, Byte[], Byte[]) LoadModule(String, Byte[], Byte[]) LoadModule(String, Byte[], Byte[])

加载带有基于通用对象文件格式 (COFF) 的映像(包含已发出的模块)或资源文件的模块(该模块相对于此程序集是内部的)。Loads the module, internal to this assembly, with a common object file format (COFF)-based image containing an emitted module, or a resource file. 还加载表示此模块的符号的原始字节。The raw bytes representing the symbols for the module are also loaded.

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

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

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

将此动态程序集保存到磁盘。Saves this dynamic assembly to disk.

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

将此动态程序集保存到磁盘中,在程序集可执行文件和目标平台中指定代码的特性。Saves this dynamic assembly to disk, specifying the nature of code in the assembly's executables and the target platform.

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

使用指定的自定义特性 Blob 设置此程序集上的自定义特性。Set a custom attribute on this assembly using a specified custom attribute blob.

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

使用自定义特性生成器设置此程序集的自定义特性。Set a custom attribute on this assembly using a custom attribute builder.

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

设置此动态程序集的入口点,假设正在生成控制台应用程序。Sets the entry point for this dynamic assembly, assuming that a console application is being built.

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

设置此程序集的入口点并定义正在构建的可移植执行文件(PE 文件)的类型。Sets the entry point for this assembly and defines the type of the portable executable (PE file) being built.

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

返回程序集的全名,即所谓的显示名称。Returns the full name of the assembly, also known as the display name.

(Inherited from Assembly)

显式界面实现

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

返回当前实例的类型。Returns the type of the current instance.

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

将一组名称映射为对应的一组调度标识符。Maps a set of names to a corresponding set of dispatch identifiers.

_AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr) _AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr) _AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr) _AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。Retrieves the type information for an object, which can then be used to get the type information for an interface.

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

检索对象提供的类型信息接口的数量(0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

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

提供对某一对象公开的属性和方法的访问。Provides access to properties and methods exposed by an object.

事件

ModuleResolve ModuleResolve ModuleResolve ModuleResolve

当公共语言运行时类加载程序不能通过正常方法解析对程序集的内部模块的引用时发生。Occurs when the common language runtime class loader cannot resolve a reference to an internal module of an assembly through normal means.

(Inherited from Assembly)

扩展方法

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

检索应用于指定程序集的指定类型的自定义特性。Retrieves a custom attribute of a specified type that is applied to a specified assembly.

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

检索应用于指定程序集的指定类型的自定义特性。Retrieves a custom attribute of a specified type that is applied to a specified assembly.

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

检索应用于指定程序集的自定义特性集合。Retrieves a collection of custom attributes that are applied to a specified assembly.

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

检索应用于指定程序集的指定类型的自定义特性集合Retrieves a collection of custom attributes of a specified type that are applied to a specified assembly.

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

检索应用于指定程序集的指定类型的自定义特性集合Retrieves a collection of custom attributes of a specified type that are applied to a specified assembly.

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

确定是否将指定类型的任何自定义属性应用于指定的程序集。Indicates whether custom attributes of a specified type are applied to a specified assembly.

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

安全性

ReflectionPermission
当调用后期绑定机制通过如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联枚举:MemberAccessAssociated enumeration: MemberAccess.

适用于

另请参阅