AppDomain.Load Método

Definición

Carga un Assembly en este dominio de aplicación.Loads an Assembly into this application domain.

Sobrecargas

Load(Byte[])

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly.

Load(AssemblyName)

Carga un Assembly a partir de su AssemblyName.Loads an Assembly given its AssemblyName.

Load(String)

Carga un Assembly a partir de su nombre de presentación.Loads an Assembly given its display name.

Load(Byte[], Byte[])

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. También se cargan los bytes sin formato que representan los símbolos del Assembly.The raw bytes representing the symbols for the Assembly are also loaded.

Load(AssemblyName, Evidence)
Obsoleto.
Obsoleto.

Carga un Assembly a partir de su AssemblyName.Loads an Assembly given its AssemblyName.

Load(String, Evidence)
Obsoleto.
Obsoleto.

Carga un Assembly a partir de su nombre de presentación.Loads an Assembly given its display name.

Load(Byte[], Byte[], Evidence)
Obsoleto.
Obsoleto.

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. También se cargan los bytes sin formato que representan los símbolos del Assembly.The raw bytes representing the symbols for the Assembly are also loaded.

Load(Byte[])

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly.

public:
 System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly);
public:
 virtual System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly);
public System.Reflection.Assembly Load (byte[] rawAssembly);
member this.Load : byte[] -> System.Reflection.Assembly
abstract member Load : byte[] -> System.Reflection.Assembly
override this.Load : byte[] -> System.Reflection.Assembly
Public Function Load (rawAssembly As Byte()) As Assembly

Parámetros

rawAssembly
Byte[]

Matriz de tipo byte que es una imagen basada en COFF que contiene un ensamblado emitido.An array of type byte that is a COFF-based image containing an emitted assembly.

Devoluciones

Assembly

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

rawAssembly es null.rawAssembly is null.

rawAssembly no es un ensamblado válido.rawAssembly is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior del Common Language Runtime está cargada actualmente y rawAssembly se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and rawAssembly was compiled with a later version.

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

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Ejemplos

En el siguiente ejemplo se muestra el uso de la carga de un ensamblado sin formato.The following sample demonstrates the use of loading a raw assembly.

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::IO;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void InstantiateMyType( AppDomain^ domain )
{
   try
   {
      
      // You must supply a valid fully qualified assembly name here.
      domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyType" );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}


// Loads the content of a file to a Byte array.
array<Byte>^ loadFile( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   array<Byte>^buffer = gcnew array<Byte>((int)fs->Length);
   fs->Read( buffer, 0, buffer->Length );
   fs->Close();
   return buffer;
}


// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
void EmitAssembly( AppDomain^ domain )
{
   AssemblyName^ assemblyName = gcnew AssemblyName;
   assemblyName->Name = "MyAssembly";
   AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Save );
   ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyModule", "temp.dll", true );
   TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyType", TypeAttributes::Public );
   ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
   ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
   ilGenerator->EmitWriteLine( "MyType instantiated!" );
   ilGenerator->Emit( OpCodes::Ret );
   typeBuilder->CreateType();
   assemblyBuilder->Save( "temp.dll" );
}

ref class Resolver
{
public:
   static Assembly^ MyResolver( Object^ sender, ResolveEventArgs^ args )
   {
      AppDomain^ domain = dynamic_cast<AppDomain^>(sender);
      
      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly( domain );
      array<Byte>^rawAssembly = loadFile( "temp.dll" );
      array<Byte>^rawSymbolStore = loadFile( "temp.pdb" );
      Assembly^ assembly = domain->Load( rawAssembly, rawSymbolStore );
      return assembly;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   InstantiateMyType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Resolver::MyResolver );
   InstantiateMyType( currentDomain ); // OK!
}

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

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

      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);

      InstantiateMyType(currentDomain);   // OK!
   }

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

   // Loads the content of a file to a byte array.
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();

      return buffer;
   }

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);

      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }

   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      assemblyBuilder.Save("temp.dll");
   }
}
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyType(currentDomain)      ' Failed!

      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolver
      
      InstantiateMyType(currentDomain)      ' OK!
   End Sub
   
   
   Sub InstantiateMyType(domain As AppDomain)
      Try
     ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   
   ' Loads the content of a file to a byte array. 
   Function loadFile(filename As String) As Byte()
      Dim fs As New FileStream(filename, FileMode.Open)
      Dim buffer(CInt(fs.Length - 1)) As Byte
      fs.Read(buffer, 0, buffer.Length)
      fs.Close()
      
      Return buffer
   End Function 'loadFile
   
   
   Function MyResolver(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Dim domain As AppDomain = DirectCast(sender, AppDomain)
      
      ' Once the files are generated, this call is
      ' actually no longer necessary.
      EmitAssembly(domain)
      
      Dim rawAssembly As Byte() = loadFile("temp.dll")
      Dim rawSymbolStore As Byte() = loadFile("temp.pdb")
      Dim myAssembly As System.Reflection.Assembly = domain.Load(rawAssembly, rawSymbolStore)
      
      Return myAssembly
   End Function 'MyResolver
   
   
   ' Creates a dynamic assembly with symbol information
   ' and saves them to temp.dll and temp.pdb
   Sub EmitAssembly(domain As AppDomain)
      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", True)
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public)
      
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      ilGenerator.EmitWriteLine("MyType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      assemblyBuilder.Save("temp.dll")
   End Sub

End Module 'Test

Comentarios

A partir de .NET Framework 4.NET Framework 4 , el nivel de confianza de un ensamblado que se carga mediante este método es el mismo que el nivel de confianza del dominio de aplicación.Beginning with the .NET Framework 4.NET Framework 4, the trust level of an assembly that is loaded by using this method is the same as the trust level of the application domain.

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden llamar al Assembly.Load método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método como CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Se aplica a

Load(AssemblyName)

Carga un Assembly a partir de su AssemblyName.Loads an Assembly given its AssemblyName.

public:
 System::Reflection::Assembly ^ Load(System::Reflection::AssemblyName ^ assemblyRef);
public:
 virtual System::Reflection::Assembly ^ Load(System::Reflection::AssemblyName ^ assemblyRef);
public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef);
member this.Load : System.Reflection.AssemblyName -> System.Reflection.Assembly
abstract member Load : System.Reflection.AssemblyName -> System.Reflection.Assembly
override this.Load : System.Reflection.AssemblyName -> System.Reflection.Assembly
Public Function Load (assemblyRef As AssemblyName) As Assembly

Parámetros

assemblyRef
AssemblyName

Objeto que describe el ensamblado que se va a cargar.An object that describes the assembly to load.

Devoluciones

Assembly

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

assemblyRef es null.assemblyRef is null.

No se ha encontrado assemblyRef.assemblyRef is not found.

assemblyRef no es un ensamblado válido.assemblyRef is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior del Common Language Runtime está cargada actualmente y assemblyRef se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyRef was compiled with a later version.

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

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Comentarios

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden llamar al Assembly.Load método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método como CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Si ya se ha cargado una versión del ensamblado solicitado, este método devuelve el ensamblado cargado, aunque se solicite una versión diferente.If a version of the requested assembly is already loaded, this method returns the loaded assembly, even if a different version is requested.

No se recomienda proporcionar un nombre de ensamblado parcial para assemblyRef .Supplying a partial assembly name for assemblyRef is not recommended. (Un nombre parcial omite uno o varios de los tokens de referencia cultural, versión o clave pública.(A partial name omits one or more of culture, version, or public key token. En el caso de las sobrecargas que toman una cadena en lugar de un AssemblyName objeto, "myAssembly, version = 1.0.0.0" es un ejemplo de un nombre parcial y "myAssembly, version = 1.0.0.0, Culture = neutral, PublicKeyToken = 18ab3442da84b47" es un ejemplo de un nombre completo). El uso de nombres parciales tiene un efecto negativo en el rendimiento.For overloads that take a string instead of an AssemblyName object, "MyAssembly, Version=1.0.0.0" is an example of a partial name and "MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=18ab3442da84b47" is an example of a full name.) Using partial names has a negative effect on performance. Además, un nombre de ensamblado parcial solo puede cargar un ensamblado de la caché global de ensamblados si hay una copia exacta del ensamblado en el directorio base de la aplicación ( BaseDirectory o AppDomainSetup.ApplicationBase ).In addition, a partial assembly name can load an assembly from the global assembly cache only if there is an exact copy of the assembly in the application base directory (BaseDirectory or AppDomainSetup.ApplicationBase).

Si el AppDomain objeto actual representa el dominio A de aplicación y Load se llama al método desde el dominio de aplicación B , el ensamblado se carga en ambos dominios de aplicación.If the current AppDomain object represents application domain A, and the Load method is called from application domain B, the assembly is loaded into both application domains. Por ejemplo, el código siguiente se carga MyAssembly en el nuevo dominio de aplicación ChildDomain y también en el dominio de aplicación donde se ejecuta el código:For example, the following code loads MyAssembly into the new application domain ChildDomain and also into the application domain where the code executes:

AppDomain^ ad = AppDomain::CreateDomain("ChildDomain");
ad->Load("MyAssembly");
AppDomain ad = AppDomain.CreateDomain("ChildDomain");
ad.Load("MyAssembly");
Dim ad As AppDomain  = AppDomain.CreateDomain("ChildDomain")
ad.Load("MyAssembly")

El ensamblado se carga en ambos dominios porque no se Assembly deriva de MarshalByRefObject y, por tanto, no se pueden calcular las referencias del valor devuelto del Load método.The assembly is loaded into both domains because Assembly does not derive from MarshalByRefObject, and therefore the return value of the Load method cannot be marshaled. En su lugar, el Common Language Runtime intenta cargar el ensamblado en el dominio de aplicación que realiza la llamada.Instead, the common language runtime tries to load the assembly into the calling application domain. Los ensamblados que se cargan en los dos dominios de aplicación pueden ser diferentes si la configuración de la ruta de acceso de los dos dominios de aplicación es diferente.The assemblies that are loaded into the two application domains might be different if the path settings for the two application domains are different.

Nota

Si AssemblyName.Name se establecen tanto la propiedad como la AssemblyName.CodeBase propiedad, el primer intento de cargar el ensamblado usa el nombre para mostrar (incluida la versión, la referencia cultural, etc., tal y como lo devuelve la Assembly.FullName propiedad).If both the AssemblyName.Name property and the AssemblyName.CodeBase property are set, the first attempt to load the assembly uses the display name (including version, culture, and so on, as returned by the Assembly.FullName property). Si no se encuentra el archivo, la CodeBase propiedad se usa para buscar el ensamblado.If the file is not found, the CodeBase property is used to search for the assembly. Si se encuentra el ensamblado mediante CodeBase , el nombre para mostrar coincide con el ensamblado.If the assembly is found using CodeBase, the display name is matched against the assembly. Si se produce un error en la coincidencia, FileLoadException se produce una excepción.If the match fails, a FileLoadException is thrown.

Se aplica a

Load(String)

Carga un Assembly a partir de su nombre de presentación.Loads an Assembly given its display name.

public:
 System::Reflection::Assembly ^ Load(System::String ^ assemblyString);
public:
 virtual System::Reflection::Assembly ^ Load(System::String ^ assemblyString);
public System.Reflection.Assembly Load (string assemblyString);
member this.Load : string -> System.Reflection.Assembly
abstract member Load : string -> System.Reflection.Assembly
override this.Load : string -> System.Reflection.Assembly
Public Function Load (assemblyString As String) As Assembly

Parámetros

assemblyString
String

Nombre para mostrar del ensamblado.The display name of the assembly. Vea FullName.See FullName.

Devoluciones

Assembly

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

assemblyString es nullassemblyString is null

No se ha encontrado assemblyString.assemblyString is not found.

assemblyString no es un ensamblado válido.assemblyString is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior del Common Language Runtime está cargada actualmente y assemblyString se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyString was compiled with a later version.

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

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Comentarios

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden llamar al Assembly.Load método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método como CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Se aplica a

Load(Byte[], Byte[])

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. También se cargan los bytes sin formato que representan los símbolos del Assembly.The raw bytes representing the symbols for the Assembly are also loaded.

public:
 System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly, cli::array <System::Byte> ^ rawSymbolStore);
public:
 virtual System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly, cli::array <System::Byte> ^ rawSymbolStore);
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[]? rawSymbolStore);
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore);
member this.Load : byte[] * byte[] -> System.Reflection.Assembly
abstract member Load : byte[] * byte[] -> System.Reflection.Assembly
override this.Load : byte[] * byte[] -> System.Reflection.Assembly
Public Function Load (rawAssembly As Byte(), rawSymbolStore As Byte()) As Assembly

Parámetros

rawAssembly
Byte[]

Matriz de tipo byte que es una imagen basada en COFF que contiene un ensamblado emitido.An array of type byte that is a COFF-based image containing an emitted assembly.

rawSymbolStore
Byte[]

Matriz de tipo byte que contiene los bytes sin formato que representan los símbolos del ensamblado.An array of type byte containing the raw bytes representing the symbols for the assembly.

Devoluciones

Assembly

Ensamblado cargado.The loaded assembly.

Implementaciones

Excepciones

rawAssembly es null.rawAssembly is null.

rawAssembly no es un ensamblado válido.rawAssembly is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior del Common Language Runtime está cargada actualmente y rawAssembly se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and rawAssembly was compiled with a later version.

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

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Ejemplos

En el siguiente ejemplo se muestra el uso de la carga de un ensamblado sin formato.The following sample demonstrates the use of loading a raw assembly.

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::IO;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void InstantiateMyType( AppDomain^ domain )
{
   try
   {
      
      // You must supply a valid fully qualified assembly name here.
      domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyType" );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}


// Loads the content of a file to a Byte array.
array<Byte>^ loadFile( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   array<Byte>^buffer = gcnew array<Byte>((int)fs->Length);
   fs->Read( buffer, 0, buffer->Length );
   fs->Close();
   return buffer;
}


// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
void EmitAssembly( AppDomain^ domain )
{
   AssemblyName^ assemblyName = gcnew AssemblyName;
   assemblyName->Name = "MyAssembly";
   AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Save );
   ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyModule", "temp.dll", true );
   TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyType", TypeAttributes::Public );
   ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
   ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
   ilGenerator->EmitWriteLine( "MyType instantiated!" );
   ilGenerator->Emit( OpCodes::Ret );
   typeBuilder->CreateType();
   assemblyBuilder->Save( "temp.dll" );
}

ref class Resolver
{
public:
   static Assembly^ MyResolver( Object^ sender, ResolveEventArgs^ args )
   {
      AppDomain^ domain = dynamic_cast<AppDomain^>(sender);
      
      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly( domain );
      array<Byte>^rawAssembly = loadFile( "temp.dll" );
      array<Byte>^rawSymbolStore = loadFile( "temp.pdb" );
      Assembly^ assembly = domain->Load( rawAssembly, rawSymbolStore );
      return assembly;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   InstantiateMyType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Resolver::MyResolver );
   InstantiateMyType( currentDomain ); // OK!
}

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

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

      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);

      InstantiateMyType(currentDomain);   // OK!
   }

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

   // Loads the content of a file to a byte array.
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();

      return buffer;
   }

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);

      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }

   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      assemblyBuilder.Save("temp.dll");
   }
}
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyType(currentDomain)      ' Failed!

      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolver
      
      InstantiateMyType(currentDomain)      ' OK!
   End Sub
   
   
   Sub InstantiateMyType(domain As AppDomain)
      Try
     ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   
   ' Loads the content of a file to a byte array. 
   Function loadFile(filename As String) As Byte()
      Dim fs As New FileStream(filename, FileMode.Open)
      Dim buffer(CInt(fs.Length - 1)) As Byte
      fs.Read(buffer, 0, buffer.Length)
      fs.Close()
      
      Return buffer
   End Function 'loadFile
   
   
   Function MyResolver(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Dim domain As AppDomain = DirectCast(sender, AppDomain)
      
      ' Once the files are generated, this call is
      ' actually no longer necessary.
      EmitAssembly(domain)
      
      Dim rawAssembly As Byte() = loadFile("temp.dll")
      Dim rawSymbolStore As Byte() = loadFile("temp.pdb")
      Dim myAssembly As System.Reflection.Assembly = domain.Load(rawAssembly, rawSymbolStore)
      
      Return myAssembly
   End Function 'MyResolver
   
   
   ' Creates a dynamic assembly with symbol information
   ' and saves them to temp.dll and temp.pdb
   Sub EmitAssembly(domain As AppDomain)
      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", True)
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public)
      
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      ilGenerator.EmitWriteLine("MyType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      assemblyBuilder.Save("temp.dll")
   End Sub

End Module 'Test

Comentarios

A partir de .NET Framework 4.NET Framework 4 , el nivel de confianza de un ensamblado que se carga mediante este método es el mismo que el nivel de confianza del dominio de aplicación.Beginning with the .NET Framework 4.NET Framework 4, the trust level of an assembly that is loaded by using this method is the same as the trust level of the application domain.

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden llamar al Assembly.Load método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método como CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Se aplica a

Load(AssemblyName, 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 Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Precaución

Use an overload that does not take an Evidence parameter

Carga un Assembly a partir de su AssemblyName.Loads an Assembly given its AssemblyName.

public:
 virtual System::Reflection::Assembly ^ Load(System::Reflection::AssemblyName ^ assemblyRef, System::Security::Policy::Evidence ^ assemblySecurity);
public:
 System::Reflection::Assembly ^ Load(System::Reflection::AssemblyName ^ assemblyRef, System::Security::Policy::Evidence ^ assemblySecurity);
public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity);
[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 Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity);
abstract member Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<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 Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
abstract member Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
member this.Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
abstract member Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : System.Reflection.AssemblyName * System.Security.Policy.Evidence -> System.Reflection.Assembly
Public Function Load (assemblyRef As AssemblyName, assemblySecurity As Evidence) As Assembly

Parámetros

assemblyRef
AssemblyName

Objeto que describe el ensamblado que se va a cargar.An object that describes the assembly to load.

assemblySecurity
Evidence

Evidencia para cargar el ensamblado.Evidence for loading the assembly.

Devoluciones

Assembly

Ensamblado cargado.The loaded assembly.

Implementaciones

Atributos

Excepciones

assemblyRef es nullassemblyRef is null

No se ha encontrado assemblyRef.assemblyRef is not found.

assemblyRef no es un ensamblado válido.assemblyRef is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior del Common Language Runtime está cargada actualmente y assemblyRef se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyRef was compiled with a later version.

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

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Comentarios

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden llamar al Assembly.Load método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método como CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Se aplica a

Load(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 Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Precaución

Use an overload that does not take an Evidence parameter

Carga un Assembly a partir de su nombre de presentación.Loads an Assembly given its display name.

public:
 virtual System::Reflection::Assembly ^ Load(System::String ^ assemblyString, System::Security::Policy::Evidence ^ assemblySecurity);
public:
 System::Reflection::Assembly ^ Load(System::String ^ assemblyString, System::Security::Policy::Evidence ^ assemblySecurity);
public System.Reflection.Assembly Load (string assemblyString, System.Security.Policy.Evidence assemblySecurity);
[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 Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Reflection.Assembly Load (string assemblyString, System.Security.Policy.Evidence assemblySecurity);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
public System.Reflection.Assembly Load (string assemblyString, System.Security.Policy.Evidence assemblySecurity);
abstract member Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<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 Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")>]
abstract member Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
member this.Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
abstract member Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : string * System.Security.Policy.Evidence -> System.Reflection.Assembly
Public Function Load (assemblyString As String, assemblySecurity As Evidence) As Assembly

Parámetros

assemblyString
String

Nombre para mostrar del ensamblado.The display name of the assembly. Vea FullName.See FullName.

assemblySecurity
Evidence

Evidencia para cargar el ensamblado.Evidence for loading the assembly.

Devoluciones

Assembly

Ensamblado cargado.The loaded assembly.

Implementaciones

Atributos

Excepciones

assemblyString es nullassemblyString is null

No se ha encontrado assemblyString.assemblyString is not found.

assemblyString no es un ensamblado válido.assemblyString is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior del Common Language Runtime está cargada actualmente y assemblyString se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyString was compiled with a later version.

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

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Comentarios

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden llamar al Assembly.Load método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método como CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Se aplica a

Load(Byte[], Byte[], 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 Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.

Precaución

Use an overload that does not take an Evidence parameter

Carga el Assembly con una imagen basada en el formato COFF (Common Object File Format) que contiene un Assembly emitido.Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. También se cargan los bytes sin formato que representan los símbolos del Assembly.The raw bytes representing the symbols for the Assembly are also loaded.

public:
 virtual System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly, cli::array <System::Byte> ^ rawSymbolStore, System::Security::Policy::Evidence ^ securityEvidence);
public:
 System::Reflection::Assembly ^ Load(cli::array <System::Byte> ^ rawAssembly, cli::array <System::Byte> ^ rawSymbolStore, System::Security::Policy::Evidence ^ securityEvidence);
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence);
[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 Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
public System.Reflection.Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence);
abstract member Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<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 Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")>]
abstract member Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
member this.Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
[<System.Obsolete("Use an overload that does not take an Evidence parameter")>]
abstract member Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
override this.Load : byte[] * byte[] * System.Security.Policy.Evidence -> System.Reflection.Assembly
Public Function Load (rawAssembly As Byte(), rawSymbolStore As Byte(), securityEvidence As Evidence) As Assembly

Parámetros

rawAssembly
Byte[]

Matriz de tipo byte que es una imagen basada en COFF que contiene un ensamblado emitido.An array of type byte that is a COFF-based image containing an emitted assembly.

rawSymbolStore
Byte[]

Matriz de tipo byte que contiene los bytes sin formato que representan los símbolos del ensamblado.An array of type byte containing the raw bytes representing the symbols for the assembly.

securityEvidence
Evidence

Evidencia para cargar el ensamblado.Evidence for loading the assembly.

Devoluciones

Assembly

Ensamblado cargado.The loaded assembly.

Implementaciones

Atributos

Excepciones

rawAssembly es null.rawAssembly is null.

rawAssembly no es un ensamblado válido.rawAssembly is not a valid assembly.

o bien-or- La versión 2.0 u otra posterior del Common Language Runtime está cargada actualmente y rawAssembly se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and rawAssembly was compiled with a later version.

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

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

securityEvidence no es null.securityEvidence is not null. Cuando no se habilita la directiva CAS heredada, securityEvidence debe ser null.When legacy CAS policy is not enabled, securityEvidence should be null.

Ejemplos

En el siguiente ejemplo se muestra el uso de la carga de un ensamblado sin formato.The following sample demonstrates the use of loading a raw assembly.

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::IO;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void InstantiateMyType( AppDomain^ domain )
{
   try
   {
      
      // You must supply a valid fully qualified assembly name here.
      domain->CreateInstance( "Assembly text name, Version, Culture, PublicKeyToken", "MyType" );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}


// Loads the content of a file to a Byte array.
array<Byte>^ loadFile( String^ filename )
{
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   array<Byte>^buffer = gcnew array<Byte>((int)fs->Length);
   fs->Read( buffer, 0, buffer->Length );
   fs->Close();
   return buffer;
}


// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
void EmitAssembly( AppDomain^ domain )
{
   AssemblyName^ assemblyName = gcnew AssemblyName;
   assemblyName->Name = "MyAssembly";
   AssemblyBuilder^ assemblyBuilder = domain->DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess::Save );
   ModuleBuilder^ moduleBuilder = assemblyBuilder->DefineDynamicModule( "MyModule", "temp.dll", true );
   TypeBuilder^ typeBuilder = moduleBuilder->DefineType( "MyType", TypeAttributes::Public );
   ConstructorBuilder^ constructorBuilder = typeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, nullptr );
   ILGenerator^ ilGenerator = constructorBuilder->GetILGenerator();
   ilGenerator->EmitWriteLine( "MyType instantiated!" );
   ilGenerator->Emit( OpCodes::Ret );
   typeBuilder->CreateType();
   assemblyBuilder->Save( "temp.dll" );
}

ref class Resolver
{
public:
   static Assembly^ MyResolver( Object^ sender, ResolveEventArgs^ args )
   {
      AppDomain^ domain = dynamic_cast<AppDomain^>(sender);
      
      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly( domain );
      array<Byte>^rawAssembly = loadFile( "temp.dll" );
      array<Byte>^rawSymbolStore = loadFile( "temp.pdb" );
      Assembly^ assembly = domain->Load( rawAssembly, rawSymbolStore );
      return assembly;
   }

};

int main()
{
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   InstantiateMyType( currentDomain ); // Failed!
   currentDomain->AssemblyResolve += gcnew ResolveEventHandler( Resolver::MyResolver );
   InstantiateMyType( currentDomain ); // OK!
}

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

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

      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);

      InstantiateMyType(currentDomain);   // OK!
   }

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

   // Loads the content of a file to a byte array.
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();

      return buffer;
   }

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);

      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }

   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      assemblyBuilder.Save("temp.dll");
   }
}
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Emit

Module Test
   
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
      InstantiateMyType(currentDomain)      ' Failed!

      AddHandler currentDomain.AssemblyResolve, AddressOf MyResolver
      
      InstantiateMyType(currentDomain)      ' OK!
   End Sub
   
   
   Sub InstantiateMyType(domain As AppDomain)
      Try
     ' You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
      Catch e As Exception
         Console.WriteLine(e.Message)
      End Try
   End Sub
   
   
   ' Loads the content of a file to a byte array. 
   Function loadFile(filename As String) As Byte()
      Dim fs As New FileStream(filename, FileMode.Open)
      Dim buffer(CInt(fs.Length - 1)) As Byte
      fs.Read(buffer, 0, buffer.Length)
      fs.Close()
      
      Return buffer
   End Function 'loadFile
   
   
   Function MyResolver(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
      Dim domain As AppDomain = DirectCast(sender, AppDomain)
      
      ' Once the files are generated, this call is
      ' actually no longer necessary.
      EmitAssembly(domain)
      
      Dim rawAssembly As Byte() = loadFile("temp.dll")
      Dim rawSymbolStore As Byte() = loadFile("temp.pdb")
      Dim myAssembly As System.Reflection.Assembly = domain.Load(rawAssembly, rawSymbolStore)
      
      Return myAssembly
   End Function 'MyResolver
   
   
   ' Creates a dynamic assembly with symbol information
   ' and saves them to temp.dll and temp.pdb
   Sub EmitAssembly(domain As AppDomain)
      Dim assemblyName As New AssemblyName()
      assemblyName.Name = "MyAssembly"
      
      Dim assemblyBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save)
      Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", True)
      Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public)
      
      Dim constructorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Nothing)
      Dim ilGenerator As ILGenerator = constructorBuilder.GetILGenerator()
      ilGenerator.EmitWriteLine("MyType instantiated!")
      ilGenerator.Emit(OpCodes.Ret)
      
      typeBuilder.CreateType()
      
      assemblyBuilder.Save("temp.dll")
   End Sub

End Module 'Test

Comentarios

A partir de .NET Framework 4.NET Framework 4 , el nivel de confianza de un ensamblado que se carga mediante este método es el mismo que el nivel de confianza del dominio de aplicación.Beginning with the .NET Framework 4.NET Framework 4, the trust level of an assembly that is loaded by using this method is the same as the trust level of the application domain.

Este método solo se debe usar para cargar un ensamblado en el dominio de aplicación actual.This method should be used only to load an assembly into the current application domain. Este método se proporciona por comodidad para los llamadores de interoperabilidad que no pueden llamar al Assembly.Load método estático.This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. Para cargar ensamblados en otros dominios de aplicación, use un método como CreateInstanceAndUnwrap .To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap.

Para obtener información común a todas las sobrecargas de este método, vea la Load(AssemblyName) sobrecarga del método.For information that is common to all overloads of this method, see the Load(AssemblyName) method overload.

Se aplica a