AppDomain.DefineDynamicAssembly Método

Definición

Define un ensamblado dinámico en el dominio de aplicación actual.Defines a dynamic assembly in the current application domain.

Sobrecargas

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean, IEnumerable<CustomAttributeBuilder>)
Obsoleto.
Obsoleto.

Define un ensamblado dinámico con el nombre especificado, el modo de acceso, el directorio de almacenamiento, la evidencia, las solicitudes de permiso, la opción de sincronización y los atributos personalizados.Defines a dynamic assembly with the specified name, access mode, storage directory, evidence, permission requests, synchronization option, and custom attributes.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean)
Obsoleto.
Obsoleto.

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso, el directorio de almacenamiento, la evidencia, las solicitudes de permiso y la opción de sincronización.Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, permission requests, and synchronization option.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet)
Obsoleto.
Obsoleto.

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso, el directorio de almacenamiento, la evidencia y las solicitudes de permiso.Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, and permission requests.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, PermissionSet, PermissionSet, PermissionSet)
Obsoleto.
Obsoleto.

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso, el directorio de almacenamiento y las solicitudes de permiso.Defines a dynamic assembly using the specified name, access mode, storage directory, and permission requests.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence, PermissionSet, PermissionSet, PermissionSet)
Obsoleto.
Obsoleto.

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso, la evidencia y las solicitudes de permiso.Defines a dynamic assembly using the specified name, access mode, evidence, and permission requests.

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

Define un ensamblado dinámico usando el nombre, el modo de acceso, el directorio de almacenamiento y la opción de sincronización especificados.Defines a dynamic assembly using the specified name, access mode, storage directory, and synchronization option.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, PermissionSet, PermissionSet, PermissionSet)
Obsoleto.
Obsoleto.

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso y las solicitudes de permiso.Defines a dynamic assembly using the specified name, access mode, and permission requests.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence)
Obsoleto.
Obsoleto.

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso, el directorio de almacenamiento y la evidencia.Defines a dynamic assembly using the specified name, access mode, storage directory, and evidence.

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

Define un ensamblado dinámico con el nombre, el modo de acceso y los atributos personalizados especificados, y usando el origen indicado para su contexto de seguridad.Defines a dynamic assembly with the specified name, access mode, and custom attributes, and using the specified source for its security context.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String)

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso y el directorio de almacenamiento.Defines a dynamic assembly using the specified name, access mode, and storage directory.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence)
Obsoleto.
Obsoleto.

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso y la evidencia.Defines a dynamic assembly using the specified name, access mode, and evidence.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)

Define un ensamblado dinámico con el nombre especificado, el modo de acceso y los atributos personalizados.Defines a dynamic assembly with the specified name, access mode, and custom attributes.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)

Define un ensamblado dinámico con el nombre y modo de acceso especificados.Defines a dynamic assembly with the specified name and access mode.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean, IEnumerable<CustomAttributeBuilder>)

Precaución

Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Precaución

Declarative security for assembly level is no longer enforced

Define un ensamblado dinámico con el nombre especificado, el modo de acceso, el directorio de almacenamiento, la evidencia, las solicitudes de permiso, la opción de sincronización y los atributos personalizados.Defines a dynamic assembly with the specified name, access mode, storage directory, evidence, permission requests, synchronization option, and custom attributes.

public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir, System::Security::Policy::Evidence ^ evidence, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions, bool isSynchronized, System::Collections::Generic::IEnumerable<System::Reflection::Emit::CustomAttributeBuilder ^> ^ assemblyAttributes);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions, bool isSynchronized, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes);
[System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions, bool isSynchronized, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes);
[System.Obsolete("Declarative security for assembly level is no longer enforced")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions, bool isSynchronized, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes);
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet * bool * seq<System.Reflection.Emit.CustomAttributeBuilder> -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet * bool * seq<System.Reflection.Emit.CustomAttributeBuilder> -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet * bool * seq<System.Reflection.Emit.CustomAttributeBuilder> -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, dir As String, evidence As Evidence, requiredPermissions As PermissionSet, optionalPermissions As PermissionSet, refusedPermissions As PermissionSet, isSynchronized As Boolean, assemblyAttributes As IEnumerable(Of CustomAttributeBuilder)) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.The mode in which the dynamic assembly will be accessed.

dir
String

Nombre del directorio donde se guardará el ensamblado dinámico.The name of the directory where the dynamic assembly will be saved. Si dir es null, se usa el directorio actual.If dir is null, the current directory is used.

evidence
Evidence

Evidencia suministrada para el ensamblado dinámico.The evidence that is supplied for the dynamic assembly. La evidencia se usa sin modificaciones como conjunto final de evidencia para la resolución de directivas.The evidence is used unaltered as the final set of evidence used for policy resolution.

requiredPermissions
PermissionSet

Solicitud de permisos requeridos.The required permissions request.

optionalPermissions
PermissionSet

Solicitud de permisos opcionales.The optional permissions request.

refusedPermissions
PermissionSet

Solicitud de permisos rechazados.The refused permissions request.

isSynchronized
Boolean

true para sincronizar la creación de módulos, tipos y miembros en el ensamblado dinámico; en caso contrario, false.true to synchronize the creation of modules, types, and members in the dynamic assembly; otherwise, false.

assemblyAttributes
IEnumerable<CustomAttributeBuilder>

Lista enumerable de atributos que se va a aplicarse al ensamblado o null si no hay ningún atributo.An enumerable list of attributes to be applied to the assembly, or null if there are no attributes.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Atributos

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name starts with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Comentarios

Utilice esta sobrecarga del método para especificar atributos que no funcionan correctamente a menos que se apliquen cuando se crea un ensamblado dinámico.Use this method overload to specify attributes that do not work correctly unless they are applied when a dynamic assembly is created. Por ejemplo, los atributos de seguridad como SecurityTransparentAttribute y SecurityCriticalAttribute no funcionan correctamente si se agregan después de que se haya creado un ensamblado dinámico.For example, security attributes such as SecurityTransparentAttribute and SecurityCriticalAttribute do not work correctly if they are added after a dynamic assembly has been created.

Las solicitudes de permiso especificadas para los requiredPermissions optionalPermissions parámetros, y refusedPermissions solo se utilizan si evidence también se proporciona el parámetro, o si el ensamblado dinámico se guarda y se recarga en la memoria.The permission requests specified for the requiredPermissions, optionalPermissions, and refusedPermissions parameters are used only if the evidence parameter is also supplied, or if the dynamic assembly is saved and reloaded into memory.

Nota

Al desarrollar código que emite ensamblados dinámicos, se recomienda incluir la SecurityPermissionFlag.SkipVerification marca en el refusedPermissions parámetro.When you develop code that emits dynamic assemblies, we recommend that you include the SecurityPermissionFlag.SkipVerification flag in the refusedPermissions parameter. La inclusión de esta marca garantiza que se comprobará el lenguaje intermedio de Microsoft (MSIL).The inclusion of this flag ensures that the Microsoft intermediate language (MSIL) will be verified. Esta técnica detectará la generación involuntaria de código no comprobable, que de otro modo es muy difícil de detectar.This technique will detect the unintentional generation of unverifiable code, which otherwise is very difficult to detect. Una limitación de esta técnica es que también hace que SecurityException se produzca cuando se usa con código que exige plena confianza.A limitation of this technique is that it also causes SecurityException to be thrown when it is used with code that demands full trust.

Solo los llamadores de plena confianza pueden proporcionar evidencia al definir un dinámico Assembly .Only fully trusted callers can supply evidence when defining a dynamic Assembly. El tiempo de ejecución asigna Evidence a a través de la Directiva de seguridad para determinar los permisos concedidos.The runtime maps the Evidence through the security policy to determine the granted permissions. Los llamadores de confianza parcial deben proporcionar null el evidence parámetro.Partially trusted callers must supply null for the evidence parameter. Si evidence es null , el tiempo de ejecución copia los conjuntos de permisos (es decir, los conjuntos de concesión y denegación actuales) del ensamblado del llamador en el ensamblado dinámico que se está definiendo y marca la Directiva como resuelta.If evidence is null, the runtime copies the permission sets (that is, the current grant and deny sets) from the caller's assembly to the dynamic assembly that is being defined, and marks the policy as resolved.

Si el ensamblado dinámico se guarda en el disco, las cargas posteriores obtendrán concesiones en función de las directivas que están asociadas a la ubicación donde se guardó el ensamblado dinámico.If the dynamic assembly is saved to disk, subsequent loads will get grants based on policies that are associated with the location where the dynamic assembly was saved.

Si isSynchronized es true , se sincronizarán los métodos siguientes del resultante AssemblyBuilder : DefineDynamicModule , DefineResource , AddResourceFile , GetDynamicModule , SetEntryPoint y Save .If isSynchronized is true, the following methods of the resulting AssemblyBuilder will be synchronized: DefineDynamicModule, DefineResource, AddResourceFile, GetDynamicModule, SetEntryPoint, and Save. Si se llama a dos de estos métodos en subprocesos diferentes, uno se bloqueará hasta que se complete el otro.If two of these methods are called on different threads, one will block until the other is completed.

Esta sobrecarga del método se introduce en el .NET Framework 3,5.This method overload is introduced in the .NET Framework 3.5.

Consulte también

Se aplica a

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean)

Precaución

Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Precaución

Declarative security for assembly level is no longer enforced

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso, el directorio de almacenamiento, la evidencia, las solicitudes de permiso y la opción de sincronización.Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, permission requests, and synchronization option.

public:
 virtual System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir, System::Security::Policy::Evidence ^ evidence, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions, bool isSynchronized);
public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir, System::Security::Policy::Evidence ^ evidence, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions, bool isSynchronized);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions, bool isSynchronized);
[System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions, bool isSynchronized);
[System.Obsolete("Declarative security for assembly level is no longer enforced")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions, bool isSynchronized);
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet * bool -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet * bool -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet * bool -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet * bool -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet * bool -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet * bool -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet * bool -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, dir As String, evidence As Evidence, requiredPermissions As PermissionSet, optionalPermissions As PermissionSet, refusedPermissions As PermissionSet, isSynchronized As Boolean) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.The mode in which the dynamic assembly will be accessed.

dir
String

Nombre del directorio donde se guardará el ensamblado dinámico.The name of the directory where the dynamic assembly will be saved. Si dir es null, el directorio predeterminado es el directorio actual.If dir is null, the directory defaults to the current directory.

evidence
Evidence

Evidencia suministrada para el ensamblado dinámico.The evidence supplied for the dynamic assembly. La evidencia se usa sin modificaciones como conjunto final de evidencia para la resolución de directivas.The evidence is used unaltered as the final set of evidence used for policy resolution.

requiredPermissions
PermissionSet

Solicitud de permisos requeridos.The required permissions request.

optionalPermissions
PermissionSet

Solicitud de permisos opcionales.The optional permissions request.

refusedPermissions
PermissionSet

Solicitud de permisos rechazados.The refused permissions request.

isSynchronized
Boolean

true para sincronizar la creación de módulos, tipos y miembros en el ensamblado dinámico; en caso contrario, false.true to synchronize the creation of modules, types, and members in the dynamic assembly; otherwise, false.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Implementaciones

Atributos

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name begins with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Ejemplos

En el ejemplo siguiente se muestra el DefineDynamicAssembly método y el AssemblyResolve evento.The following sample demonstrates the DefineDynamicAssembly method and AssemblyResolve event.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombres de ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class Test
{
public:
   static void InstantiateMyDynamicType( AppDomain^ domain )
   {
      try
      {
         
         // You must supply a valid fully qualified assembly name here.
         domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType" );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
   {
      return DefineDynamicAssembly( dynamic_cast<AppDomain^>(sender) );
   }

   static Assembly^ DefineDynamicAssembly( AppDomain^ domain )
   {
      
      // Build a dynamic assembly using Reflection Emit API.
      AssemblyName^ assemblyName = gcnew AssemblyName;
      assemblyName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Run );
      ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyDynamicModule" );
      TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyDynamicType", TypeAttributes::Public );
      ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
      ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
      ilGenerator->EmitWriteLine( "MyDynamicType instantiated!" );
      ilGenerator->Emit( OpCodes::Ret );
      typeBuilder->CreateType();
      return assemblyBuilder;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   Test::InstantiateMyDynamicType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Test::MyResolveEventHandler );
   Test::InstantiateMyDynamicType( currentDomain ); // OK!
}

using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }

   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.

      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();

      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyDynamicType(currentDomain)   'Failed!
      
      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolveEventHandler
      
      InstantiateMyDynamicType(currentDomain)   'OK!
   End Sub
   
   Sub InstantiateMyDynamicType(domain As AppDomain)
      Try
         ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   Function MyResolveEventHandler(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Return DefineDynamicAssembly(DirectCast(sender, AppDomain))
   End Function 'MyResolveEventHandler
   
   Function DefineDynamicAssembly(domain As AppDomain) As System.Reflection.Assembly
      ' Build a dynamic assembly using Reflection Emit API.

      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyDynamicAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule")
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public)
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      Return assemblyBuilder
   End Function 'DefineDynamicAssembly

End Module 'Test 

Comentarios

Las solicitudes de permiso especificadas para requiredPermissions , optionalPermissions y refusedPermissions solo se utilizan si evidence se ha proporcionado también, o si el ensamblado dinámico se guarda y se recarga en la memoria.The permission requests specified for requiredPermissions, optionalPermissions, and refusedPermissions are used only if evidence is also supplied, or if the dynamic assembly is saved and reloaded into memory.

Nota

Durante el desarrollo de código que emite ensamblados dinámicos, se recomienda que incluya SecurityPermissionFlag.SkipVerification en refusedPermissions .During the development of code that emits dynamic assemblies, it is recommended that you include SecurityPermissionFlag.SkipVerification in refusedPermissions. Incluir SkipVerification en el refusedPermissions parámetro garantiza que se compruebe el MSIL.Including SkipVerification in the refusedPermissions parameter ensures that the MSIL is verified. Una limitación de esta técnica es que también hace que SecurityException se produzca cuando se usa con código que exige plena confianza.A limitation of this technique is that it also causes SecurityException to be thrown when used with code that demands full trust.

Solo los llamadores de plena confianza pueden proporcionar su evidencia al definir un dinámico Assembly .Only fully trusted callers can supply their evidence when defining a dynamic Assembly. El tiempo de ejecución asignará el Evidence a través de la Directiva de seguridad para determinar los permisos concedidos.The runtime will map the Evidence through the security policy to determine the granted permissions. Los llamadores de confianza parcial deben proporcionar null el evidence parámetro.Partially trusted callers must supply null for the evidence parameter. Si evidence es null , el motor en tiempo de ejecución copia los conjuntos de permisos, es decir, los conjuntos de concesión y denegación actuales, del llamador Assembly en el dinámico Assembly que se define y marca la Directiva como resuelta.If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's Assembly to the dynamic Assembly being defined and marks policy as resolved.

Si el dinámico Assembly se guarda en el disco, las cargas posteriores obtendrán concesiones en función de las directivas asociadas a la ubicación en la que Assembly se guardó.If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.

Si isSynchronized es true , se sincronizarán los métodos siguientes del resultante AssemblyBuilder : DefineDynamicModule , DefineResource , AddResourceFile , GetDynamicModule , SetEntryPoint y Save .If isSynchronized is true, the following methods of the resulting AssemblyBuilder will be synchronized: DefineDynamicModule, DefineResource, AddResourceFile, GetDynamicModule, SetEntryPoint, and Save. Si se llama a dos de estos métodos en diferentes subprocesos, uno se bloqueará hasta que se complete el otro.If two of these methods are called on different threads, one will block until the other completes.

Se aplica a

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet)

Precaución

Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. Please see http://go.microsoft.com/fwlink/?LinkId=155570 for more information.

Precaución

Declarative security for assembly level is no longer enforced

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso, el directorio de almacenamiento, la evidencia y las solicitudes de permiso.Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, and permission requests.

public:
 virtual System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir, System::Security::Policy::Evidence ^ evidence, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions);
public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir, System::Security::Policy::Evidence ^ evidence, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
[System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default.  Please see http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
[System.Obsolete("Declarative security for assembly level is no longer enforced")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default.  Please see http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, dir As String, evidence As Evidence, requiredPermissions As PermissionSet, optionalPermissions As PermissionSet, refusedPermissions As PermissionSet) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.The mode in which the dynamic assembly will be accessed.

dir
String

Nombre del directorio donde se guardará el ensamblado.The name of the directory where the assembly will be saved. Si dir es null, el directorio predeterminado es el directorio actual.If dir is null, the directory defaults to the current directory.

evidence
Evidence

Evidencia suministrada para el ensamblado dinámico.The evidence supplied for the dynamic assembly. La evidencia se usa sin modificaciones como conjunto final de evidencia para la resolución de directivas.The evidence is used unaltered as the final set of evidence used for policy resolution.

requiredPermissions
PermissionSet

Solicitud de permisos requeridos.The required permissions request.

optionalPermissions
PermissionSet

Solicitud de permisos opcionales.The optional permissions request.

refusedPermissions
PermissionSet

Solicitud de permisos rechazados.The refused permissions request.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Implementaciones

Atributos

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name begins with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Ejemplos

En el ejemplo siguiente se muestra el DefineDynamicAssembly método y el AssemblyResolve evento.The following sample demonstrates the DefineDynamicAssembly method and AssemblyResolve event.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombres de ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class Test
{
public:
   static void InstantiateMyDynamicType( AppDomain^ domain )
   {
      try
      {
         
         // You must supply a valid fully qualified assembly name here.
         domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType" );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
   {
      return DefineDynamicAssembly( dynamic_cast<AppDomain^>(sender) );
   }

   static Assembly^ DefineDynamicAssembly( AppDomain^ domain )
   {
      
      // Build a dynamic assembly using Reflection Emit API.
      AssemblyName^ assemblyName = gcnew AssemblyName;
      assemblyName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Run );
      ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyDynamicModule" );
      TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyDynamicType", TypeAttributes::Public );
      ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
      ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
      ilGenerator->EmitWriteLine( "MyDynamicType instantiated!" );
      ilGenerator->Emit( OpCodes::Ret );
      typeBuilder->CreateType();
      return assemblyBuilder;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   Test::InstantiateMyDynamicType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Test::MyResolveEventHandler );
   Test::InstantiateMyDynamicType( currentDomain ); // OK!
}

using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }

   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.

      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();

      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyDynamicType(currentDomain)   'Failed!
      
      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolveEventHandler
      
      InstantiateMyDynamicType(currentDomain)   'OK!
   End Sub
   
   Sub InstantiateMyDynamicType(domain As AppDomain)
      Try
         ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   Function MyResolveEventHandler(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Return DefineDynamicAssembly(DirectCast(sender, AppDomain))
   End Function 'MyResolveEventHandler
   
   Function DefineDynamicAssembly(domain As AppDomain) As System.Reflection.Assembly
      ' Build a dynamic assembly using Reflection Emit API.

      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyDynamicAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule")
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public)
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      Return assemblyBuilder
   End Function 'DefineDynamicAssembly

End Module 'Test 

Comentarios

Las solicitudes de permiso especificadas para requiredPermissions , optionalPermissions y refusedPermissions solo se utilizan si evidence se ha proporcionado también, o si el ensamblado dinámico se guarda y se recarga en la memoria.The permission requests specified for requiredPermissions, optionalPermissions, and refusedPermissions are used only if evidence is also supplied, or if the dynamic assembly is saved and reloaded into memory.

Nota

Durante el desarrollo de código que emite ensamblados dinámicos, se recomienda que incluya SecurityPermissionFlag.SkipVerification en refusedPermissions .During the development of code that emits dynamic assemblies, it is recommended that you include SecurityPermissionFlag.SkipVerification in refusedPermissions. Incluir SkipVerification en el refusedPermissions parámetro garantiza que se compruebe el MSIL.Including SkipVerification in the refusedPermissions parameter ensures that the MSIL is verified. Una limitación de esta técnica es que también hace que SecurityException se produzca cuando se usa con código que exige plena confianza.A limitation of this technique is that it also causes SecurityException to be thrown when used with code that demands full trust.

Solo los llamadores de plena confianza pueden proporcionar su evidence al definir un dinámico Assembly .Only fully trusted callers can supply their evidence when defining a dynamic Assembly. El tiempo de ejecución asignará el Evidence a través de la Directiva de seguridad para determinar los permisos concedidos.The runtime will map the Evidence through the security policy to determine the granted permissions. Los llamadores de confianza parcial deben proporcionar un valor null evidence .Partially trusted callers must supply a null evidence. Si evidence es null , el motor en tiempo de ejecución copia los conjuntos de permisos, es decir, los conjuntos de concesión y denegación actuales, del llamador Assembly en el dinámico Assembly que se define y marca la Directiva como resuelta.If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's Assembly to the dynamic Assembly being defined and marks policy as resolved.

Si el dinámico Assembly se guarda en el disco, las cargas posteriores obtendrán concesiones en función de las directivas asociadas a la ubicación en la que Assembly se guardó.If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.

Este método solo se debe usar para definir un ensamblado dinámico en el dominio de aplicación actual.This method should only be used to define a dynamic assembly in the current application domain. Para obtener más información, vea la Load(AssemblyName) sobrecarga del método.For more information, see the Load(AssemblyName) method overload.

Se aplica a

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, PermissionSet, PermissionSet, PermissionSet)

Precaución

Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Precaución

Declarative security for assembly level is no longer enforced

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso, el directorio de almacenamiento y las solicitudes de permiso.Defines a dynamic assembly using the specified name, access mode, storage directory, and permission requests.

public:
 virtual System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions);
public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
[System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
[System.Obsolete("Declarative security for assembly level is no longer enforced")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, dir As String, requiredPermissions As PermissionSet, optionalPermissions As PermissionSet, refusedPermissions As PermissionSet) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.The mode in which the dynamic assembly will be accessed.

dir
String

Nombre del directorio donde se guardará el ensamblado.The name of the directory where the assembly will be saved. Si dir es null, el directorio predeterminado es el directorio actual.If dir is null, the directory defaults to the current directory.

requiredPermissions
PermissionSet

Solicitud de permisos requeridos.The required permissions request.

optionalPermissions
PermissionSet

Solicitud de permisos opcionales.The optional permissions request.

refusedPermissions
PermissionSet

Solicitud de permisos rechazados.The refused permissions request.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Implementaciones

Atributos

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name begins with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Ejemplos

En el ejemplo siguiente se muestra el DefineDynamicAssembly método y el AssemblyResolve evento.The following sample demonstrates the DefineDynamicAssembly method and AssemblyResolve event.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombres de ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class Test
{
public:
   static void InstantiateMyDynamicType( AppDomain^ domain )
   {
      try
      {
         
         // You must supply a valid fully qualified assembly name here.
         domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType" );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
   {
      return DefineDynamicAssembly( dynamic_cast<AppDomain^>(sender) );
   }

   static Assembly^ DefineDynamicAssembly( AppDomain^ domain )
   {
      
      // Build a dynamic assembly using Reflection Emit API.
      AssemblyName^ assemblyName = gcnew AssemblyName;
      assemblyName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Run );
      ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyDynamicModule" );
      TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyDynamicType", TypeAttributes::Public );
      ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
      ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
      ilGenerator->EmitWriteLine( "MyDynamicType instantiated!" );
      ilGenerator->Emit( OpCodes::Ret );
      typeBuilder->CreateType();
      return assemblyBuilder;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   Test::InstantiateMyDynamicType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Test::MyResolveEventHandler );
   Test::InstantiateMyDynamicType( currentDomain ); // OK!
}

using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }

   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.

      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();

      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyDynamicType(currentDomain)   'Failed!
      
      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolveEventHandler
      
      InstantiateMyDynamicType(currentDomain)   'OK!
   End Sub
   
   Sub InstantiateMyDynamicType(domain As AppDomain)
      Try
         ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   Function MyResolveEventHandler(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Return DefineDynamicAssembly(DirectCast(sender, AppDomain))
   End Function 'MyResolveEventHandler
   
   Function DefineDynamicAssembly(domain As AppDomain) As System.Reflection.Assembly
      ' Build a dynamic assembly using Reflection Emit API.

      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyDynamicAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule")
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public)
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      Return assemblyBuilder
   End Function 'DefineDynamicAssembly

End Module 'Test 

Comentarios

Las solicitudes de permiso especificadas para requiredPermissions , optionalPermissions y refusedPermissions no se utilizan a menos que el ensamblado dinámico se haya guardado y recargado en la memoria.The permission requests specified for requiredPermissions, optionalPermissions, and refusedPermissions are not used unless the dynamic assembly has been saved and reloaded into memory. Para especificar solicitudes de permisos para un ensamblado transitorio que nunca se guarda en el disco, use una sobrecarga del DefineDynamicAssembly método que especifique la evidencia y los permisos solicitados, y proporcione un Evidence objeto.To specify permission requests for a transient assembly that is never saved to disk, use an overload of the DefineDynamicAssembly method that specifies evidence as well as requested permissions, and supply an Evidence object.

Nota

Durante el desarrollo de código que emite ensamblados dinámicos, se recomienda que use una sobrecarga del DefineDynamicAssembly método que especifique Evidence y permisos, proporcione la evidencia que desee que tenga el ensamblado dinámico e incluya SecurityPermissionFlag.SkipVerification en refusedPermissions .During the development of code that emits dynamic assemblies, it is recommended that you use an overload of the DefineDynamicAssembly method that specifies evidence and permissions, supply the evidence you want the dynamic assembly to have, and include SecurityPermissionFlag.SkipVerification in refusedPermissions. Incluir SkipVerification en el refusedPermissions parámetro garantiza que se compruebe el MSIL.Including SkipVerification in the refusedPermissions parameter ensures that the MSIL is verified. Una limitación de esta técnica es que también hace que SecurityException se produzca cuando se usa con código que exige plena confianza.A limitation of this technique is that it also causes SecurityException to be thrown when used with code that demands full trust.

Este método solo se debe usar para definir un ensamblado dinámico en el dominio de aplicación actual.This method should only be used to define a dynamic assembly in the current application domain. Para obtener más información, vea la Load(AssemblyName) sobrecarga del método.For more information, see the Load(AssemblyName) method overload.

Se aplica a

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence, PermissionSet, PermissionSet, PermissionSet)

Precaución

Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Precaución

Declarative security for assembly level is no longer enforced

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso, la evidencia y las solicitudes de permiso.Defines a dynamic assembly using the specified name, access mode, evidence, and permission requests.

public:
 virtual System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::Security::Policy::Evidence ^ evidence, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions);
public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::Security::Policy::Evidence ^ evidence, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
[System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
[System.Obsolete("Declarative security for assembly level is no longer enforced")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, evidence As Evidence, requiredPermissions As PermissionSet, optionalPermissions As PermissionSet, refusedPermissions As PermissionSet) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.The mode in which the dynamic assembly will be accessed.

evidence
Evidence

Evidencia suministrada para el ensamblado dinámico.The evidence supplied for the dynamic assembly. La evidencia se usa sin modificaciones como conjunto final de evidencia para la resolución de directivas.The evidence is used unaltered as the final set of evidence used for policy resolution.

requiredPermissions
PermissionSet

Solicitud de permisos requeridos.The required permissions request.

optionalPermissions
PermissionSet

Solicitud de permisos opcionales.The optional permissions request.

refusedPermissions
PermissionSet

Solicitud de permisos rechazados.The refused permissions request.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Implementaciones

Atributos

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name begins with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Ejemplos

En el ejemplo siguiente se muestra el DefineDynamicAssembly método y el AssemblyResolve evento.The following sample demonstrates the DefineDynamicAssembly method and AssemblyResolve event.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombres de ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class Test
{
public:
   static void InstantiateMyDynamicType( AppDomain^ domain )
   {
      try
      {
         
         // You must supply a valid fully qualified assembly name here.
         domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType" );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
   {
      return DefineDynamicAssembly( dynamic_cast<AppDomain^>(sender) );
   }

   static Assembly^ DefineDynamicAssembly( AppDomain^ domain )
   {
      
      // Build a dynamic assembly using Reflection Emit API.
      AssemblyName^ assemblyName = gcnew AssemblyName;
      assemblyName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Run );
      ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyDynamicModule" );
      TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyDynamicType", TypeAttributes::Public );
      ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
      ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
      ilGenerator->EmitWriteLine( "MyDynamicType instantiated!" );
      ilGenerator->Emit( OpCodes::Ret );
      typeBuilder->CreateType();
      return assemblyBuilder;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   Test::InstantiateMyDynamicType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Test::MyResolveEventHandler );
   Test::InstantiateMyDynamicType( currentDomain ); // OK!
}

using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }

   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.

      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();

      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyDynamicType(currentDomain)   'Failed!
      
      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolveEventHandler
      
      InstantiateMyDynamicType(currentDomain)   'OK!
   End Sub
   
   Sub InstantiateMyDynamicType(domain As AppDomain)
      Try
         ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   Function MyResolveEventHandler(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Return DefineDynamicAssembly(DirectCast(sender, AppDomain))
   End Function 'MyResolveEventHandler
   
   Function DefineDynamicAssembly(domain As AppDomain) As System.Reflection.Assembly
      ' Build a dynamic assembly using Reflection Emit API.

      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyDynamicAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule")
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public)
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      Return assemblyBuilder
   End Function 'DefineDynamicAssembly

End Module 'Test 

Comentarios

Las solicitudes de permiso especificadas para requiredPermissions , optionalPermissions y refusedPermissions solo se utilizan si evidence se ha proporcionado también, o si el ensamblado dinámico se guarda y se recarga en la memoria.The permission requests specified for requiredPermissions, optionalPermissions, and refusedPermissions are used only if evidence is also supplied, or if the dynamic assembly is saved and reloaded into memory.

Nota

Durante el desarrollo de código que emite ensamblados dinámicos, se recomienda que incluya SecurityPermissionFlag.SkipVerification en refusedPermissions .During the development of code that emits dynamic assemblies, it is recommended that you include SecurityPermissionFlag.SkipVerification in refusedPermissions. Incluir SkipVerification en el refusedPermissions parámetro garantiza que se compruebe el MSIL.Including SkipVerification in the refusedPermissions parameter ensures that the MSIL is verified. Una limitación de esta técnica es que también hace que SecurityException se produzca cuando se usa con código que exige plena confianza.A limitation of this technique is that it also causes SecurityException to be thrown when used with code that demands full trust.

Solo los llamadores de plena confianza pueden proporcionar su evidence al definir un dinámico Assembly .Only fully trusted callers can supply their evidence when defining a dynamic Assembly. El tiempo de ejecución asignará el Evidence a través de la Directiva de seguridad para determinar los permisos concedidos.The runtime will map the Evidence through the security policy to determine the granted permissions. Los llamadores de confianza parcial deben proporcionar un valor null evidence .Partially trusted callers must supply a null evidence. Si evidence es null , el motor en tiempo de ejecución copia los conjuntos de permisos, es decir, los conjuntos de concesión y denegación actuales, del llamador Assembly en el dinámico Assembly que se define y marca la Directiva como resuelta.If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's Assembly to the dynamic Assembly being defined and marks policy as resolved.

Si el dinámico Assembly se guarda en el disco, las cargas posteriores obtendrán concesiones en función de las directivas asociadas a la ubicación en la que Assembly se guardó.If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.

Este método solo se debe usar para definir un ensamblado dinámico en el dominio de aplicación actual.This method should only be used to define a dynamic assembly in the current application domain. Para obtener más información, vea la Load(AssemblyName) sobrecarga del método.For more information, see the Load(AssemblyName) method overload.

Se aplica a

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

Define un ensamblado dinámico usando el nombre, el modo de acceso, el directorio de almacenamiento y la opción de sincronización especificados.Defines a dynamic assembly using the specified name, access mode, storage directory, and synchronization option.

public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir, bool isSynchronized, System::Collections::Generic::IEnumerable<System::Reflection::Emit::CustomAttributeBuilder ^> ^ assemblyAttributes);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, bool isSynchronized, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes);
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * bool * seq<System.Reflection.Emit.CustomAttributeBuilder> -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, dir As String, isSynchronized As Boolean, assemblyAttributes As IEnumerable(Of CustomAttributeBuilder)) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.The mode in which the dynamic assembly will be accessed.

dir
String

Nombre del directorio donde se guardará el ensamblado dinámico.The name of the directory where the dynamic assembly will be saved. Si dir es null, se usa el directorio actual.If dir is null, the current directory is used.

isSynchronized
Boolean

true para sincronizar la creación de módulos, tipos y miembros en el ensamblado dinámico; en caso contrario, false.true to synchronize the creation of modules, types, and members in the dynamic assembly; otherwise, false.

assemblyAttributes
IEnumerable<CustomAttributeBuilder>

Lista enumerable de atributos que se va a aplicarse al ensamblado o null si no hay ningún atributo.An enumerable list of attributes to be applied to the assembly, or null if there are no attributes.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name starts with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Comentarios

Utilice esta sobrecarga del método para especificar atributos que no funcionan correctamente a menos que se apliquen cuando se crea un ensamblado dinámico.Use this method overload to specify attributes that do not work correctly unless they are applied when a dynamic assembly is created. Por ejemplo, los atributos de seguridad como SecurityTransparentAttribute y SecurityCriticalAttribute no funcionan correctamente si se agregan después de que se haya creado un ensamblado dinámico.For example, security attributes such as SecurityTransparentAttribute and SecurityCriticalAttribute do not work correctly if they are added after a dynamic assembly has been created.

Si isSynchronized es true , se sincronizarán los métodos siguientes del resultante AssemblyBuilder : DefineDynamicModule , DefineResource , AddResourceFile , GetDynamicModule , SetEntryPoint y Save .If isSynchronized is true, the following methods of the resulting AssemblyBuilder will be synchronized: DefineDynamicModule, DefineResource, AddResourceFile, GetDynamicModule, SetEntryPoint, and Save. Si se llama a dos de estos métodos en subprocesos diferentes, uno se bloqueará hasta que se complete el otro.If two of these methods are called on different threads, one will block until the other is completed.

Consulte también

Se aplica a

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, PermissionSet, PermissionSet, PermissionSet)

Precaución

Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Precaución

Declarative security for assembly level is no longer enforced

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso y las solicitudes de permiso.Defines a dynamic assembly using the specified name, access mode, and permission requests.

public:
 virtual System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions);
public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::Security::PermissionSet ^ requiredPermissions, System::Security::PermissionSet ^ optionalPermissions, System::Security::PermissionSet ^ refusedPermissions);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
[System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default.  See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
[System.Obsolete("Declarative security for assembly level is no longer enforced")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions);
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default.  See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.PermissionSet * System.Security.PermissionSet * System.Security.PermissionSet -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, requiredPermissions As PermissionSet, optionalPermissions As PermissionSet, refusedPermissions As PermissionSet) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.The mode in which the dynamic assembly will be accessed.

requiredPermissions
PermissionSet

Solicitud de permisos requeridos.The required permissions request.

optionalPermissions
PermissionSet

Solicitud de permisos opcionales.The optional permissions request.

refusedPermissions
PermissionSet

Solicitud de permisos rechazados.The refused permissions request.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Implementaciones

Atributos

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name begins with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Ejemplos

En el ejemplo siguiente se muestra el DefineDynamicAssembly método y el AssemblyResolve evento.The following sample demonstrates the DefineDynamicAssembly method and AssemblyResolve event.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombres de ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class Test
{
public:
   static void InstantiateMyDynamicType( AppDomain^ domain )
   {
      try
      {
         
         // You must supply a valid fully qualified assembly name here.
         domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType" );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
   {
      return DefineDynamicAssembly( dynamic_cast<AppDomain^>(sender) );
   }

   static Assembly^ DefineDynamicAssembly( AppDomain^ domain )
   {
      
      // Build a dynamic assembly using Reflection Emit API.
      AssemblyName^ assemblyName = gcnew AssemblyName;
      assemblyName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Run );
      ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyDynamicModule" );
      TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyDynamicType", TypeAttributes::Public );
      ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
      ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
      ilGenerator->EmitWriteLine( "MyDynamicType instantiated!" );
      ilGenerator->Emit( OpCodes::Ret );
      typeBuilder->CreateType();
      return assemblyBuilder;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   Test::InstantiateMyDynamicType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Test::MyResolveEventHandler );
   Test::InstantiateMyDynamicType( currentDomain ); // OK!
}

using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }

   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.

      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();

      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyDynamicType(currentDomain)   'Failed!
      
      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolveEventHandler
      
      InstantiateMyDynamicType(currentDomain)   'OK!
   End Sub
   
   Sub InstantiateMyDynamicType(domain As AppDomain)
      Try
         ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   Function MyResolveEventHandler(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Return DefineDynamicAssembly(DirectCast(sender, AppDomain))
   End Function 'MyResolveEventHandler
   
   Function DefineDynamicAssembly(domain As AppDomain) As System.Reflection.Assembly
      ' Build a dynamic assembly using Reflection Emit API.

      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyDynamicAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule")
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public)
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      Return assemblyBuilder
   End Function 'DefineDynamicAssembly

End Module 'Test 

Comentarios

Las solicitudes de permiso especificadas para requiredPermissions , optionalPermissions y refusedPermissions no se utilizan a menos que el ensamblado dinámico se haya guardado y recargado en la memoria.The permission requests specified for requiredPermissions, optionalPermissions, and refusedPermissions are not used unless the dynamic assembly has been saved and reloaded into memory. Para especificar solicitudes de permisos para un ensamblado transitorio que nunca se guarda en el disco, use una sobrecarga del DefineDynamicAssembly método que especifique la evidencia y los permisos solicitados, y proporcione un Evidence objeto.To specify permission requests for a transient assembly that is never saved to disk, use an overload of the DefineDynamicAssembly method that specifies evidence as well as requested permissions, and supply an Evidence object.

Nota

Durante el desarrollo de código que emite ensamblados dinámicos, se recomienda que use una sobrecarga del DefineDynamicAssembly método que especifique Evidence y permisos, proporcione la evidencia que desee que tenga el ensamblado dinámico e incluya SecurityPermissionFlag.SkipVerification en refusedPermissions .During the development of code that emits dynamic assemblies, it is recommended that you use an overload of the DefineDynamicAssembly method that specifies evidence and permissions, supply the evidence you want the dynamic assembly to have, and include SecurityPermissionFlag.SkipVerification in refusedPermissions. Incluir SkipVerification en el refusedPermissions parámetro garantiza que se compruebe el MSIL.Including SkipVerification in the refusedPermissions parameter ensures that the MSIL is verified. Una limitación de esta técnica es que también hace que SecurityException se produzca cuando se usa con código que exige plena confianza.A limitation of this technique is that it also causes SecurityException to be thrown when used with code that demands full trust.

Este método solo se debe usar para definir un ensamblado dinámico en el dominio de aplicación actual.This method should only be used to define a dynamic assembly in the current application domain. Para obtener más información, vea la Load(AssemblyName) sobrecarga del método.For more information, see the Load(AssemblyName) method overload .

Se aplica a

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence)

Precaución

Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of DefineDynamicAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.

Precaución

Declarative security for assembly level is no longer enforced

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso, el directorio de almacenamiento y la evidencia.Defines a dynamic assembly using the specified name, access mode, storage directory, and evidence.

public:
 virtual System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir, System::Security::Policy::Evidence ^ evidence);
public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir, System::Security::Policy::Evidence ^ evidence);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence);
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of DefineDynamicAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence);
[System.Obsolete("Declarative security for assembly level is no longer enforced")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence);
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of DefineDynamicAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, dir As String, evidence As Evidence) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.The mode in which the dynamic assembly will be accessed.

dir
String

Nombre del directorio donde se guardará el ensamblado.The name of the directory where the assembly will be saved. Si dir es null, el directorio predeterminado es el directorio actual.If dir is null, the directory defaults to the current directory.

evidence
Evidence

Evidencia suministrada para el ensamblado dinámico.The evidence supplied for the dynamic assembly. La evidencia se usa sin modificaciones como conjunto final de evidencia para la resolución de directivas.The evidence is used unaltered as the final set of evidence used for policy resolution.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Implementaciones

Atributos

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name begins with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Ejemplos

En el ejemplo siguiente se muestra el DefineDynamicAssembly método y el AssemblyResolve evento.The following sample demonstrates the DefineDynamicAssembly method and AssemblyResolve event.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombres de ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class Test
{
public:
   static void InstantiateMyDynamicType( AppDomain^ domain )
   {
      try
      {
         
         // You must supply a valid fully qualified assembly name here.
         domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType" );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
   {
      return DefineDynamicAssembly( dynamic_cast<AppDomain^>(sender) );
   }

   static Assembly^ DefineDynamicAssembly( AppDomain^ domain )
   {
      
      // Build a dynamic assembly using Reflection Emit API.
      AssemblyName^ assemblyName = gcnew AssemblyName;
      assemblyName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Run );
      ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyDynamicModule" );
      TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyDynamicType", TypeAttributes::Public );
      ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
      ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
      ilGenerator->EmitWriteLine( "MyDynamicType instantiated!" );
      ilGenerator->Emit( OpCodes::Ret );
      typeBuilder->CreateType();
      return assemblyBuilder;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   Test::InstantiateMyDynamicType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Test::MyResolveEventHandler );
   Test::InstantiateMyDynamicType( currentDomain ); // OK!
}

using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }

   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.

      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();

      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyDynamicType(currentDomain)   'Failed!
      
      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolveEventHandler
      
      InstantiateMyDynamicType(currentDomain)   'OK!
   End Sub
   
   Sub InstantiateMyDynamicType(domain As AppDomain)
      Try
         ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   Function MyResolveEventHandler(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Return DefineDynamicAssembly(DirectCast(sender, AppDomain))
   End Function 'MyResolveEventHandler
   
   Function DefineDynamicAssembly(domain As AppDomain) As System.Reflection.Assembly
      ' Build a dynamic assembly using Reflection Emit API.

      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyDynamicAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule")
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public)
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      Return assemblyBuilder
   End Function 'DefineDynamicAssembly

End Module 'Test 

Comentarios

Solo los llamadores de plena confianza pueden proporcionar su evidence al definir un dinámico Assembly .Only fully trusted callers can supply their evidence when defining a dynamic Assembly. El tiempo de ejecución asignará el Evidence a través de la Directiva de seguridad para determinar los permisos concedidos.The runtime will map the Evidence through the security policy to determine the granted permissions. Los llamadores de confianza parcial deben proporcionar un valor null evidence .Partially trusted callers must supply a null evidence. Si evidence es null , el motor en tiempo de ejecución copia los conjuntos de permisos, es decir, los conjuntos de concesión y denegación actuales, del llamador Assembly en el dinámico Assembly que se define y marca la Directiva como resuelta.If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's Assembly to the dynamic Assembly being defined and marks policy as resolved.

Si el dinámico Assembly se guarda en el disco, las cargas posteriores obtendrán concesiones en función de las directivas asociadas a la ubicación en la que Assembly se guardó.If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.

Este método solo se debe usar para definir un ensamblado dinámico en el dominio de aplicación actual.This method should only be used to define a dynamic assembly in the current application domain. Para obtener más información, vea la Load(AssemblyName) sobrecarga del método.For more information, see the Load(AssemblyName) method overload.

Nota

Durante el desarrollo de código que emite ensamblados dinámicos, se recomienda que use una sobrecarga del DefineDynamicAssembly método que especifique Evidence y permisos, proporcione la evidencia que desee que tenga el ensamblado dinámico e incluya SecurityPermissionFlag.SkipVerification en refusedPermissions .During the development of code that emits dynamic assemblies, it is recommended that you use an overload of the DefineDynamicAssembly method that specifies evidence and permissions, supply the evidence you want the dynamic assembly to have, and include SecurityPermissionFlag.SkipVerification in refusedPermissions. Incluir SkipVerification en el refusedPermissions parámetro garantiza que se compruebe el MSIL.Including SkipVerification in the refusedPermissions parameter ensures that the MSIL is verified. Una limitación de esta técnica es que también hace que SecurityException se produzca cuando se usa con código que exige plena confianza.A limitation of this technique is that it also causes SecurityException to be thrown when used with code that demands full trust.

Se aplica a

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

Define un ensamblado dinámico con el nombre, el modo de acceso y los atributos personalizados especificados, y usando el origen indicado para su contexto de seguridad.Defines a dynamic assembly with the specified name, access mode, and custom attributes, and using the specified source for its security context.

public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::Collections::Generic::IEnumerable<System::Reflection::Emit::CustomAttributeBuilder ^> ^ assemblyAttributes, System::Security::SecurityContextSource securityContextSource);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes, System.Security.SecurityContextSource securityContextSource);
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * seq<System.Reflection.Emit.CustomAttributeBuilder> * System.Security.SecurityContextSource -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, assemblyAttributes As IEnumerable(Of CustomAttributeBuilder), securityContextSource As SecurityContextSource) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso del ensamblado dinámico.The access mode for the dynamic assembly.

assemblyAttributes
IEnumerable<CustomAttributeBuilder>

Lista enumerable de atributos que se va a aplicarse al ensamblado o null si no hay ningún atributo.An enumerable list of attributes to be applied to the assembly, or null if there are no attributes.

securityContextSource
SecurityContextSource

Origen del contexto de seguridad.The source of the security context.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name starts with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

El valor de securityContextSource no era ninguno de los valores de enumeración.The value of securityContextSource was not one of the enumeration values.

Comentarios

Utilice esta sobrecarga del método para especificar atributos que no funcionan correctamente a menos que se apliquen cuando se crea un ensamblado dinámico.Use this method overload to specify attributes that do not work correctly unless they are applied when a dynamic assembly is created. Por ejemplo, los atributos de seguridad como SecurityTransparentAttribute y SecurityCriticalAttribute no funcionan correctamente si se agregan después de que se haya creado un ensamblado dinámico.For example, security attributes such as SecurityTransparentAttribute and SecurityCriticalAttribute do not work correctly if they are added after a dynamic assembly has been created.

Este método solo se debe usar para definir un ensamblado dinámico en el dominio de aplicación actual.This method should be used only to define a dynamic assembly in the current application domain. Para obtener más información sobre esta restricción, vea la Load(AssemblyName) sobrecarga del método.For more information about this restriction, see the Load(AssemblyName) method overload.

Se aplica a

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String)

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso y el directorio de almacenamiento.Defines a dynamic assembly using the specified name, access mode, and storage directory.

public:
 virtual System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir);
public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::String ^ dir);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir);
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string -> System.Reflection.Emit.AssemblyBuilder
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * string -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, dir As String) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.The mode in which the dynamic assembly will be accessed.

dir
String

Nombre del directorio donde se guardará el ensamblado.The name of the directory where the assembly will be saved. Si dir es null, el directorio predeterminado es el directorio actual.If dir is null, the directory defaults to the current directory.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Implementaciones

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name begins with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Ejemplos

En el ejemplo siguiente se muestra el DefineDynamicAssembly método y el AssemblyResolve evento.The following sample demonstrates the DefineDynamicAssembly method and AssemblyResolve event.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombres de ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class Test
{
public:
   static void InstantiateMyDynamicType( AppDomain^ domain )
   {
      try
      {
         
         // You must supply a valid fully qualified assembly name here.
         domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType" );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
   {
      return DefineDynamicAssembly( dynamic_cast<AppDomain^>(sender) );
   }

   static Assembly^ DefineDynamicAssembly( AppDomain^ domain )
   {
      
      // Build a dynamic assembly using Reflection Emit API.
      AssemblyName^ assemblyName = gcnew AssemblyName;
      assemblyName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Run );
      ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyDynamicModule" );
      TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyDynamicType", TypeAttributes::Public );
      ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
      ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
      ilGenerator->EmitWriteLine( "MyDynamicType instantiated!" );
      ilGenerator->Emit( OpCodes::Ret );
      typeBuilder->CreateType();
      return assemblyBuilder;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   Test::InstantiateMyDynamicType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Test::MyResolveEventHandler );
   Test::InstantiateMyDynamicType( currentDomain ); // OK!
}

using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }

   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.

      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();

      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyDynamicType(currentDomain)   'Failed!
      
      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolveEventHandler
      
      InstantiateMyDynamicType(currentDomain)   'OK!
   End Sub
   
   Sub InstantiateMyDynamicType(domain As AppDomain)
      Try
         ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   Function MyResolveEventHandler(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Return DefineDynamicAssembly(DirectCast(sender, AppDomain))
   End Function 'MyResolveEventHandler
   
   Function DefineDynamicAssembly(domain As AppDomain) As System.Reflection.Assembly
      ' Build a dynamic assembly using Reflection Emit API.

      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyDynamicAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule")
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public)
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      Return assemblyBuilder
   End Function 'DefineDynamicAssembly

End Module 'Test 

Comentarios

Este método solo se debe usar para definir un ensamblado dinámico en el dominio de aplicación actual.This method should only be used to define a dynamic assembly in the current application domain. Para obtener más información, vea la Load(AssemblyName) sobrecarga del método.For more information, see the Load(AssemblyName) method overload.

Nota

Durante el desarrollo de código que emite ensamblados dinámicos, se recomienda que use una sobrecarga del DefineDynamicAssembly método que especifique Evidence y permisos, proporcione la evidencia que desee que tenga el ensamblado dinámico e incluya SecurityPermissionFlag.SkipVerification en refusedPermissions .During the development of code that emits dynamic assemblies, it is recommended that you use an overload of the DefineDynamicAssembly method that specifies evidence and permissions, supply the evidence you want the dynamic assembly to have, and include SecurityPermissionFlag.SkipVerification in refusedPermissions. Incluir SkipVerification en el refusedPermissions parámetro garantiza que se compruebe el MSIL.Including SkipVerification in the refusedPermissions parameter ensures that the MSIL is verified. Una limitación de esta técnica es que también hace que SecurityException se produzca cuando se usa con código que exige plena confianza.A limitation of this technique is that it also causes SecurityException to be thrown when used with code that demands full trust.

Se aplica a

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence)

Precaución

Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Precaución

Declarative security for assembly level is no longer enforced

Define un ensamblado dinámico usando el nombre especificado, el modo de acceso y la evidencia.Defines a dynamic assembly using the specified name, access mode, and evidence.

public:
 virtual System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::Security::Policy::Evidence ^ evidence);
public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::Security::Policy::Evidence ^ evidence);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence);
[System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default.  See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence);
[System.Obsolete("Declarative security for assembly level is no longer enforced")]
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence);
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default.  See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
[<System.Obsolete("Declarative security for assembly level is no longer enforced")>]
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * System.Security.Policy.Evidence -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, evidence As Evidence) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.The mode in which the dynamic assembly will be accessed.

evidence
Evidence

Evidencia suministrada para el ensamblado dinámico.The evidence supplied for the dynamic assembly. La evidencia se usa sin modificaciones como conjunto final de evidencia para la resolución de directivas.The evidence is used unaltered as the final set of evidence used for policy resolution.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Implementaciones

Atributos

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name begins with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Ejemplos

En el ejemplo siguiente se muestra el DefineDynamicAssembly método y el AssemblyResolve evento.The following sample demonstrates the DefineDynamicAssembly method and the AssemblyResolve event.

En primer lugar, el ejemplo de código intenta crear una instancia de llamando MyDynamicType al CreateInstance método con un nombre de ensamblado no válido y detecta la excepción resultante.First, the code example tries to create an instance of MyDynamicType by calling the CreateInstance method with an invalid assembly name, and catches the resulting exception.

A continuación, el ejemplo de código agrega un controlador de eventos para el AssemblyResolve evento y, de nuevo, intenta crear una instancia de MyDynamicType .The code example then adds an event handler for the AssemblyResolve event, and again tries to create an instance ofMyDynamicType. Durante la llamada a CreateInstance , AssemblyResolve se genera el evento para el ensamblado no válido.During the call to CreateInstance, the AssemblyResolve event is raised for the invalid assembly. El controlador de eventos crea un ensamblado dinámico que contiene un tipo denominado MyDynamicType , proporciona al tipo un constructor sin parámetros y devuelve el nuevo ensamblado dinámico.The event handler creates a dynamic assembly that contains a type named MyDynamicType, gives the type a parameterless constructor, and returns the new dynamic assembly. La llamada a se CreateInstance completa correctamente y el constructor de MyDynamicType muestra un mensaje en la consola.The call to CreateInstance then finishes successfully, and the constructor for MyDynamicType displays a message at the console.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class Test
{
public:
   static void InstantiateMyDynamicType( AppDomain^ domain )
   {
      try
      {
         
         // You must supply a valid fully qualified assembly name here.
         domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType" );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
   {
      return DefineDynamicAssembly( dynamic_cast<AppDomain^>(sender) );
   }

   static Assembly^ DefineDynamicAssembly( AppDomain^ domain )
   {
      
      // Build a dynamic assembly using Reflection Emit API.
      AssemblyName^ assemblyName = gcnew AssemblyName;
      assemblyName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Run );
      ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyDynamicModule" );
      TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyDynamicType", TypeAttributes::Public );
      ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
      ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
      ilGenerator->EmitWriteLine( "MyDynamicType instantiated!" );
      ilGenerator->Emit( OpCodes::Ret );
      typeBuilder->CreateType();
      return assemblyBuilder;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   Test::InstantiateMyDynamicType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Test::MyResolveEventHandler );
   Test::InstantiateMyDynamicType( currentDomain ); // OK!
}

using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }

   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.

      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();

      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyDynamicType(currentDomain)   'Failed!
      
      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolveEventHandler
      
      InstantiateMyDynamicType(currentDomain)   'OK!
   End Sub
   
   Sub InstantiateMyDynamicType(domain As AppDomain)
      Try
         ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   Function MyResolveEventHandler(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Return DefineDynamicAssembly(DirectCast(sender, AppDomain))
   End Function 'MyResolveEventHandler
   
   Function DefineDynamicAssembly(domain As AppDomain) As System.Reflection.Assembly
      ' Build a dynamic assembly using Reflection Emit API.

      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyDynamicAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule")
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public)
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      Return assemblyBuilder
   End Function 'DefineDynamicAssembly

End Module 'Test 

Comentarios

Solo los llamadores de plena confianza pueden proporcionar su evidence al definir un dinámico Assembly .Only fully trusted callers can supply their evidence when defining a dynamic Assembly. El tiempo de ejecución asignará el Evidence a través de la Directiva de seguridad para determinar los permisos concedidos.The runtime will map the Evidence through the security policy to determine the granted permissions. Los llamadores de confianza parcial deben proporcionar un valor null evidence .Partially trusted callers must supply a null evidence. Si evidence es null , el motor en tiempo de ejecución copia los conjuntos de permisos, es decir, los conjuntos de concesión y denegación actuales, del llamador Assembly en el dinámico Assembly que se define y marca la Directiva como resuelta.If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's Assembly to the dynamic Assembly being defined and marks policy as resolved.

Si el dinámico Assembly se guarda en el disco, las cargas posteriores obtendrán concesiones en función de las directivas asociadas a la ubicación en la que Assembly se guardó.If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.

Este método solo se debe usar para definir un ensamblado dinámico en el dominio de aplicación actual.This method should only be used to define a dynamic assembly in the current application domain. Para obtener más información, vea la Load(AssemblyName) sobrecarga del método.For more information, see the Load(AssemblyName) method overload.

Nota

Durante el desarrollo de código que emite ensamblados dinámicos, se recomienda que use una sobrecarga del DefineDynamicAssembly método que especifique Evidence y permisos, proporcione la evidencia que desee que tenga el ensamblado dinámico e incluya SecurityPermissionFlag.SkipVerification en refusedPermissions .During the development of code that emits dynamic assemblies, it is recommended that you use an overload of the DefineDynamicAssembly method that specifies evidence and permissions, supply the evidence you want the dynamic assembly to have, and include SecurityPermissionFlag.SkipVerification in refusedPermissions. Incluir SkipVerification en el refusedPermissions parámetro garantiza que se compruebe el MSIL.Including SkipVerification in the refusedPermissions parameter ensures that the MSIL is verified. Una limitación de esta técnica es que también hace que SecurityException se produzca cuando se usa con código que exige plena confianza.A limitation of this technique is that it also causes SecurityException to be thrown when used with code that demands full trust.

Se aplica a

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)

Define un ensamblado dinámico con el nombre especificado, el modo de acceso y los atributos personalizados.Defines a dynamic assembly with the specified name, access mode, and custom attributes.

public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access, System::Collections::Generic::IEnumerable<System::Reflection::Emit::CustomAttributeBuilder ^> ^ assemblyAttributes);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes);
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess * seq<System.Reflection.Emit.CustomAttributeBuilder> -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess, assemblyAttributes As IEnumerable(Of CustomAttributeBuilder)) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso del ensamblado dinámico.The access mode for the dynamic assembly.

assemblyAttributes
IEnumerable<CustomAttributeBuilder>

Lista enumerable de atributos que se va a aplicarse al ensamblado o null si no hay ningún atributo.An enumerable list of attributes to be applied to the assembly, or null if there are no attributes.

Devoluciones

AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.A dynamic assembly with the specified name and features.

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name starts with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Ejemplos

En el siguiente ejemplo de código se muestra cómo crear un ensamblado dinámico que tenga SecurityTransparentAttribute .The following code sample shows how to create a dynamic assembly that has the SecurityTransparentAttribute. El atributo debe especificarse como un elemento de una matriz de CustomAttributeBuilder objetos.The attribute must be specified as an element of an array of CustomAttributeBuilder objects.

El primer paso para crear el CustomAttributeBuilder es obtener un constructor para el atributo.The first step in creating the CustomAttributeBuilder is to obtain a constructor for the attribute. El constructor no tiene parámetros, por lo que GetConstructor se llama al método con una matriz vacía de Type objetos para representar los tipos de los parámetros.The constructor has no parameters, so the GetConstructor method is called with an empty array of Type objects to represent the types of the parameters. El segundo paso es pasar el objeto resultante ConstructorInfo al constructor de la CustomAttributeBuilder clase, junto con una matriz vacía de tipo Object para representar los argumentos.The second step is to pass the resulting ConstructorInfo object to the constructor for the CustomAttributeBuilder class, together with an empty array of type Object to represent the arguments.

CustomAttributeBuilderA continuación, el resultado se pasa al DefineDynamicAssembly método como el único elemento de una matriz.The resulting CustomAttributeBuilder is then passed to the DefineDynamicAssembly method as the only element of an array.

En el código de ejemplo se define un módulo y un tipo en el nuevo ensamblado dinámico y, a continuación, se muestran los atributos del ensamblado.The example code defines a module and a type in the new dynamic assembly, and then displays the assembly's attributes.

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

void main()
{
    // Create a CustomAttributeBuilder for the assembly attribute. 
    // 
    // SecurityTransparentAttribute has a parameterless constructor, 
    // which is retrieved by passing an array of empty types for the
    // constructor's parameter types. The CustomAttributeBuilder is 
    // then created by passing the ConstructorInfo and an empty array
    // of objects to represent the parameters.
    //
    ConstructorInfo^ transparentCtor = 
        SecurityTransparentAttribute::typeid->GetConstructor(
            Type::EmptyTypes);
    CustomAttributeBuilder^ transparent = gcnew CustomAttributeBuilder(
        transparentCtor,
        gcnew array<Object^> {} );
      
    // Create a dynamic assembly using the attribute. The attribute is
    // passed as an array with one element.
    AssemblyName^ aName = gcnew AssemblyName("EmittedAssembly");
    AssemblyBuilder^ ab = AppDomain::CurrentDomain->DefineDynamicAssembly( 
        aName, 
        AssemblyBuilderAccess::Run,
        gcnew array<CustomAttributeBuilder^> { transparent } );

    ModuleBuilder^ mb = ab->DefineDynamicModule( aName->Name );
    TypeBuilder^ tb = mb->DefineType( 
        "MyDynamicType", 
        TypeAttributes::Public );
    tb->CreateType();

    Console::WriteLine("{0}\nAssembly attributes:", ab);
    for each (Attribute^ attr in ab->GetCustomAttributes(true))
    {
        Console::WriteLine("\t{0}", attr);
    }
};

/* This code example produces the following output:

EmittedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
Assembly attributes:
        System.Security.SecurityTransparentAttribute
 */
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;

class Example
{
    static void Main()
    {
        // Create a CustomAttributeBuilder for the assembly attribute.
        //
        // SecurityTransparentAttribute has a parameterless constructor,
        // which is retrieved by passing an array of empty types for the
        // constructor's parameter types. The CustomAttributeBuilder is
        // then created by passing the ConstructorInfo and an empty array
        // of objects to represent the parameters.
        //
        ConstructorInfo transparentCtor =
            typeof(SecurityTransparentAttribute).GetConstructor(
                Type.EmptyTypes);
        CustomAttributeBuilder transparent = new CustomAttributeBuilder(
            transparentCtor,
            new Object[] {} );

        // Create a dynamic assembly using the attribute. The attribute is
        // passed as an array with one element.
        AssemblyName aName = new AssemblyName("EmittedAssembly");
        AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(
            aName,
            AssemblyBuilderAccess.Run,
            new CustomAttributeBuilder[] { transparent } );

        ModuleBuilder mb = ab.DefineDynamicModule( aName.Name );
        TypeBuilder tb = mb.DefineType(
            "MyDynamicType",
            TypeAttributes.Public );
        tb.CreateType();

        Console.WriteLine("{0}\nAssembly attributes:", ab);
        foreach (Attribute attr in ab.GetCustomAttributes(true))
        {
            Console.WriteLine("\t{0}", attr);
        }
    }
}

/* This code example produces the following output:

EmittedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
Assembly attributes:
        System.Security.SecurityTransparentAttribute
 */
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Security

Module Example

    Sub Main()
    
        ' Create a CustomAttributeBuilder for the assembly attribute. 
        ' 
        ' SecurityTransparentAttribute has a parameterless constructor, 
        ' which is retrieved by passing an array of empty types for the
        ' constructor's parameter types. The CustomAttributeBuilder is 
        ' then created by passing the ConstructorInfo and an empty array
        ' of objects to represent the parameters.
        '
        Dim transparentCtor As ConstructorInfo = _
            GetType(SecurityTransparentAttribute).GetConstructor( _
                Type.EmptyTypes)
        Dim transparent As New CustomAttributeBuilder( _
            transparentCtor, _
            New Object() {} )
      
        ' Create a dynamic assembly Imports the attribute. The attribute is
        ' passed as an array with one element.
        Dim aName As New AssemblyName("EmittedAssembly")
        Dim ab As AssemblyBuilder = _
            AppDomain.CurrentDomain.DefineDynamicAssembly( _
                aName, _
                AssemblyBuilderAccess.Run, _
                New CustomAttributeBuilder() { transparent } )

        Dim mb As ModuleBuilder = ab.DefineDynamicModule( aName.Name )
        Dim tb As TypeBuilder = mb.DefineType( _
            "MyDynamicType", _
            TypeAttributes.Public )
        tb.CreateType()

        Console.WriteLine("{0}" & vbLf & "Assembly attributes:", ab)
        For Each attr As Attribute In ab.GetCustomAttributes(True)
            Console.WriteLine(vbTab & "{0}", attr)
        Next
    End Sub
End Module

' This code example produces the following output:
'
'EmittedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
'Assembly attributes:
'        System.Security.SecurityTransparentAttribute

Comentarios

Utilice esta sobrecarga del método para especificar atributos que no funcionan correctamente a menos que se apliquen cuando se crea un ensamblado dinámico.Use this method overload to specify attributes that do not work correctly unless they are applied when a dynamic assembly is created. Por ejemplo, los atributos de seguridad como SecurityTransparentAttribute y SecurityCriticalAttribute no funcionan correctamente si se agregan después de que se haya creado un ensamblado dinámico.For example, security attributes such as SecurityTransparentAttribute and SecurityCriticalAttribute do not work correctly if they are added after a dynamic assembly has been created.

Este método solo se debe usar para definir un ensamblado dinámico en el dominio de aplicación actual.This method should be used only to define a dynamic assembly in the current application domain. Para obtener más información sobre esta restricción, vea la Load(AssemblyName) sobrecarga del método.For more information about this restriction, see the Load(AssemblyName) method overload.

Esta sobrecarga del método se introduce en el .NET Framework 3,5.This method overload is introduced in the .NET Framework 3.5.

Consulte también

Se aplica a

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)

Define un ensamblado dinámico con el nombre y modo de acceso especificados.Defines a dynamic assembly with the specified name and access mode.

public:
 virtual System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access);
public:
 System::Reflection::Emit::AssemblyBuilder ^ DefineDynamicAssembly(System::Reflection::AssemblyName ^ name, System::Reflection::Emit::AssemblyBuilderAccess access);
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access);
abstract member DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess -> System.Reflection.Emit.AssemblyBuilder
override this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess -> System.Reflection.Emit.AssemblyBuilder
member this.DefineDynamicAssembly : System.Reflection.AssemblyName * System.Reflection.Emit.AssemblyBuilderAccess -> System.Reflection.Emit.AssemblyBuilder
Public Function DefineDynamicAssembly (name As AssemblyName, access As AssemblyBuilderAccess) As AssemblyBuilder

Parámetros

name
AssemblyName

Identidad única del ensamblado dinámico.The unique identity of the dynamic assembly.

access
AssemblyBuilderAccess

Modo de acceso del ensamblado dinámico.The access mode for the dynamic assembly.

Devoluciones

AssemblyBuilder

Un ensamblado dinámico con el nombre y modo de acceso especificados.A dynamic assembly with the specified name and access mode.

Implementaciones

Excepciones

name es null.name is null.

La propiedad Name de name es null.The Name property of name is null.

o bien-or- La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.The Name property of name begins with white space, or contains a forward or backward slash.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

Ejemplos

En el ejemplo siguiente se muestra el DefineDynamicAssembly método y el AssemblyResolve evento.The following sample demonstrates the DefineDynamicAssembly method and AssemblyResolve event.

Para que este ejemplo de código se ejecute, debe proporcionar el nombre completo del ensamblado.For this code example to run, you must provide the fully qualified assembly name. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea nombres de ensamblados.For information about how to obtain the fully qualified assembly name, see Assembly Names.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
ref class Test
{
public:
   static void InstantiateMyDynamicType( AppDomain^ domain )
   {
      try
      {
         
         // You must supply a valid fully qualified assembly name here.
         domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType" );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->Message );
      }

   }

   static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
   {
      return DefineDynamicAssembly( dynamic_cast<AppDomain^>(sender) );
   }

   static Assembly^ DefineDynamicAssembly( AppDomain^ domain )
   {
      
      // Build a dynamic assembly using Reflection Emit API.
      AssemblyName^ assemblyName = gcnew AssemblyName;
      assemblyName->Name = "MyDynamicAssembly";
      AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Run );
      ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyDynamicModule" );
      TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyDynamicType", TypeAttributes::Public );
      ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
      ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
      ilGenerator->EmitWriteLine( "MyDynamicType instantiated!" );
      ilGenerator->Emit( OpCodes::Ret );
      typeBuilder->CreateType();
      return assemblyBuilder;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   Test::InstantiateMyDynamicType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Test::MyResolveEventHandler );
   Test::InstantiateMyDynamicType( currentDomain ); // OK!
}

using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }

   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.

      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();

      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyDynamicType(currentDomain)   'Failed!
      
      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolveEventHandler
      
      InstantiateMyDynamicType(currentDomain)   'OK!
   End Sub
   
   Sub InstantiateMyDynamicType(domain As AppDomain)
      Try
         ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   Function MyResolveEventHandler(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Return DefineDynamicAssembly(DirectCast(sender, AppDomain))
   End Function 'MyResolveEventHandler
   
   Function DefineDynamicAssembly(domain As AppDomain) As System.Reflection.Assembly
      ' Build a dynamic assembly using Reflection Emit API.

      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyDynamicAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule")
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public)
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      Return assemblyBuilder
   End Function 'DefineDynamicAssembly

End Module 'Test 

Comentarios

Este método solo se debe usar para definir un ensamblado dinámico en el dominio de aplicación actual.This method should only be used to define a dynamic assembly in the current application domain. Para obtener más información, vea la Load(AssemblyName) sobrecarga del método.For more information, see the Load(AssemblyName) method overload.

Nota

Durante el desarrollo de código que emite ensamblados dinámicos, se recomienda que use una sobrecarga del DefineDynamicAssembly método que especifique Evidence y permisos, proporcione la evidencia que desee que tenga el ensamblado dinámico e incluya SecurityPermissionFlag.SkipVerification en refusedPermissions .During the development of code that emits dynamic assemblies, it is recommended that you use an overload of the DefineDynamicAssembly method that specifies evidence and permissions, supply the evidence you want the dynamic assembly to have, and include SecurityPermissionFlag.SkipVerification in refusedPermissions. Incluir SkipVerification en el refusedPermissions parámetro garantiza que se compruebe el MSIL.Including SkipVerification in the refusedPermissions parameter ensures that the MSIL is verified. Una limitación de esta técnica es que también hace que SecurityException se produzca cuando se usa con código que exige plena confianza.A limitation of this technique is that it also causes SecurityException to be thrown when used with code that demands full trust.

Se aplica a