Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Método AppDomain.DefineDynamicAssembly (AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean)

 

Publicado: octubre de 2016

obsoleteCodeEntityM:System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName,System.Reflection.Emit.AssemblyBuilderAccess,System.String,System.Boolean,System.Collections.Generic.IEnumerable{System.Reflection.Emit.CustomAttributeBuilder}) Nota: Esta API ahora está obsoleta.

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.

Espacio de nombres:   System
Ensamblado:  mscorlib (en mscorlib.dll)

[ObsoleteAttribute("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 AssemblyBuilder DefineDynamicAssembly(
	AssemblyName name,
	AssemblyBuilderAccess access,
	string dir,
	Evidence evidence,
	PermissionSet requiredPermissions,
	PermissionSet optionalPermissions,
	PermissionSet refusedPermissions,
	bool isSynchronized
)

Parámetros

name
Type: System.Reflection.AssemblyName

Identidad única del ensamblado dinámico.

access
Type: System.Reflection.Emit.AssemblyBuilderAccess

Modo de acceso al ensamblado dinámico.

dir
Type: System.String

Nombre del directorio donde se guardará el ensamblado dinámico. Si dir es null, el directorio predeterminado es el directorio actual.

evidence
Type: System.Security.Policy.Evidence

Evidencia suministrada para el ensamblado dinámico. La evidencia se usa sin modificaciones como conjunto final de evidencia para la resolución de directivas.

requiredPermissions
Type: System.Security.PermissionSet

Solicitud de permisos requeridos.

optionalPermissions
Type: System.Security.PermissionSet

Solicitud de permisos opcionales.

refusedPermissions
Type: System.Security.PermissionSet

Solicitud de permisos rechazados.

isSynchronized
Type: System.Boolean

true para sincronizar la creación de módulos, tipos y miembros en el ensamblado dinámico; en caso contrario, false.

Valor devuelto

Type: System.Reflection.Emit.AssemblyBuilder

Ensamblado dinámico con el nombre y las características especificados.

Exception Condition
ArgumentNullException

El valor de name es null.

ArgumentException

La propiedad Name de name es null.

O bien

La propiedad Name de name empieza con un espacio en blanco o contiene una barra diagonal o una barra diagonal inversa.

AppDomainUnloadedException

La operación se intenta en un dominio de aplicación descargado.

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.

System_CAPS_noteNota

During the development of code that emits dynamic assemblies, it is recommended that you include F:System.Security.Permissions.SecurityPermissionFlag.SkipVerification in refusedPermissions. Including F:System.Security.Permissions.SecurityPermissionFlag.SkipVerification in the refusedPermissions parameter ensures that the MSIL is verified. A limitation of this technique is that it also causes T:System.Security.SecurityException to be thrown when used with code that demands full trust.

Only fully trusted callers can supply their evidence when defining a dynamic T:System.Reflection.Assembly. The runtime will map the T:System.Security.Policy.Evidence through the security policy to determine the granted permissions. Partially trusted callers must supply null for the evidence parameter. If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's T:System.Reflection.Assembly to the dynamic T:System.Reflection.Assembly being defined and marks policy as resolved.

If the dynamic T:System.Reflection.Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the T:System.Reflection.Assembly was saved.

If isSynchronized is true, the following methods of the resulting T:System.Reflection.Emit.AssemblyBuilder will be synchronized: Overload:System.Reflection.Emit.AssemblyBuilder.DefineDynamicModule, Overload:System.Reflection.Emit.AssemblyBuilder.DefineResource, Overload:System.Reflection.Emit.AssemblyBuilder.AddResourceFile, M:System.Reflection.Emit.AssemblyBuilder.GetDynamicModule(System.String), Overload:System.Reflection.Emit.AssemblyBuilder.SetEntryPoint, and Overload:System.Reflection.Emit.AssemblyBuilder.Save. If two of these methods are called on different threads, one will block until the other completes.

The following sample demonstrates the M:System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName,System.Reflection.Emit.AssemblyBuilderAccess) method and E:System.AppDomain.AssemblyResolve event.

For this code example to run, you must provide the fully qualified assembly name. For information about how to obtain the fully qualified assembly name, see Assembly Names.

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;
   }
}

SecurityPermission

to load an assembly with evidence. Associated enumeration: F:System.Security.Permissions.SecurityPermissionFlag.ControlEvidence.

.NET Framework
Disponible desde 1.1
Volver al principio
Mostrar: