AppDomain.Load 方法

定義

Assembly 載入這個應用程式定義域中。

多載

Load(Byte[])

載入具備通用物件檔案格式 (COFF) 影像 (包含發出的 Assembly) 的 Assembly

Load(AssemblyName)

載入提供了 AssemblyNameAssembly

Load(String)

載入提供了顯示名稱的 Assembly

Load(Byte[], Byte[])

載入具備通用物件檔案格式 (COFF) 影像 (包含發出的 Assembly) 的 Assembly。 也會載入代表 Assembly 符號且未經處理的位元組。

Load(AssemblyName, Evidence)
已淘汰.

載入提供了 AssemblyNameAssembly

Load(String, Evidence)
已淘汰.

載入提供了顯示名稱的 Assembly

Load(Byte[], Byte[], Evidence)
已淘汰.

載入具備通用物件檔案格式 (COFF) 影像 (包含發出的 Assembly) 的 Assembly。 也會載入代表 Assembly 符號且未經處理的位元組。

Load(Byte[])

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

載入具備通用物件檔案格式 (COFF) 影像 (包含發出的 Assembly) 的 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

參數

rawAssembly
Byte[]

byte 類型的陣列,這是包含發出組件之以 COFF 為基礎的影像。

傳回

載入的組件。

實作

例外狀況

rawAssemblynull

rawAssembly 不是目前載入運行時間的有效元件。

嘗試對卸載的應用程式定義域執行作業。

使用兩個不同的辨識項載入組件或模組兩次。

範例

下列範例示範如何使用載入原始元件。

若要執行此程式碼範例,您必須提供完整元件名稱。 如需如何取得完整元件名稱的詳細資訊,請參閱 元件名稱

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 LoadRawSnippet {
   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");
   }
}
open System
open System.IO
open System.Reflection
open System.Reflection.Emit

let instantiateMyType (domain: AppDomain) =
    try
        // You must supply a valid fully qualified assembly name here.
        domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
        |> ignore  
    with e ->
        printfn $"{e.Message}"

// Loads the content of a file to a byte array.
let loadFile filename =
    use fs = new FileStream(filename, FileMode.Open)
    let buffer = Array.zeroCreate<byte> (int fs.Length)
    fs.Read(buffer, 0, buffer.Length) |> ignore
    fs.Close()
    buffer

// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
let emitAssembly (domain: AppDomain) =
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyAssembly"

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

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

    typeBuilder.CreateType() |> ignore

    assemblyBuilder.Save "temp.dll"

let myResolver (sender: obj) (args: ResolveEventArgs) =
    let domain = sender :?> AppDomain

    // Once the files are generated, this call is
    // actually no longer necessary.
    emitAssembly domain

    let rawAssembly = loadFile "temp.dll"
    let rawSymbolStore = loadFile "temp.pdb"
    domain.Load(rawAssembly, rawSymbolStore)

let currentDomain = AppDomain.CurrentDomain

instantiateMyType currentDomain   // Failed!

currentDomain.add_AssemblyResolve (ResolveEventHandler myResolver)

instantiateMyType currentDomain   // OK!
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

備註

如需此方法所有多載通用的資訊,請參閱 Load(AssemblyName) 方法多載。

從 .NET Framework 4 開始,使用此方法載入之元件的信任層級與應用程式域的信任層級相同。

適用於

Load(AssemblyName)

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

載入提供了 AssemblyNameAssembly

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

參數

assemblyRef
AssemblyName

物件,描述要載入的組件。

傳回

載入的組件。

實作

例外狀況

assemblyRefnull

找不到 assemblyRef

assemblyRef 不是目前載入運行時間的有效元件。

嘗試對卸載的應用程式定義域執行作業。

使用兩個不同的辨識項載入組件或模組兩次。

備註

這個方法應該只用來將元件載入目前的應用程式域。 這個方法可供無法呼叫靜態 Assembly.Load 方法的互操作性呼叫端使用。 若要將元件載入其他應用程式域,請使用 例如 CreateInstanceAndUnwrap的方法。

如果已載入要求的元件版本,這個方法會傳回載入的元件,即使要求不同的版本也一樣。

不建議為 提供部分元件名稱 assemblyRef 。 (部分名稱會省略一或多個文化特性、版本或公鑰令牌。對於採用字串而非 AssemblyName 物件的多載,“MyAssembly, Version=1.0.0.0” 是部分名稱的範例,而 “MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=18ab3442da84b47” 是完整名稱的範例。) 使用部分名稱對效能產生負面影響。 此外,只有在應用程式基底目錄中有元件的完整複本 (BaseDirectoryAppDomainSetup.ApplicationBase) 時,部分元件名稱才能從全域程式集緩存載入元件。

如果目前的 AppDomain 物件代表應用程式域 A,而且 Load 從應用程式域 B呼叫 方法,則會將元件載入這兩個應用程式域。 例如,下列程式代碼會載入 MyAssembly 新的應用程式域 ChildDomain ,以及載入程式代碼執行所在的應用程式域:

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

元件會載入這兩個定義域,因為 Assembly 不會衍生自 MarshalByRefObject,因此無法封送處理方法的 Load 傳回值。 相反地,Common Language Runtime 會嘗試將元件載入呼叫的應用程式域。 如果兩個應用程式域的路徑設定不同,則載入至兩個應用程式域的元件可能會不同。

注意

如果同時 AssemblyName.Name 設定 屬性和 AssemblyName.CodeBase 屬性,則第一次載入元件會使用顯示名稱 (包括版本、文化特性等,如屬性) 傳 Assembly.FullName 回。 如果找不到檔案, CodeBase 則會使用 屬性來搜尋元件。 如果使用 找到 CodeBase元件,則會比對元件顯示名稱。 如果相符項目失敗, FileLoadException 則會擲回 。

適用於

Load(String)

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

載入提供了顯示名稱的 Assembly

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

參數

assemblyString
String

組件的顯示名稱。 請參閱 FullName

傳回

載入的組件。

實作

例外狀況

assemblyStringnull

找不到 assemblyString

assemblyString 不是目前載入運行時間的有效元件。

嘗試對卸載的應用程式定義域執行作業。

使用兩個不同的辨識項載入組件或模組兩次。

備註

如需此方法所有多載通用的資訊,請參閱 Load(AssemblyName) 方法多載。

適用於

Load(Byte[], Byte[])

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

載入具備通用物件檔案格式 (COFF) 影像 (包含發出的 Assembly) 的 Assembly。 也會載入代表 Assembly 符號且未經處理的位元組。

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

參數

rawAssembly
Byte[]

byte 類型的陣列,這是包含發出組件之以 COFF 為基礎的影像。

rawSymbolStore
Byte[]

byte 類型的陣列,包含代表組件符號的未經處理位元組。

傳回

載入的組件。

實作

例外狀況

rawAssemblynull

rawAssembly 不是目前載入運行時間的有效元件。

嘗試對卸載的應用程式定義域執行作業。

使用兩個不同的辨識項載入組件或模組兩次。

範例

下列範例示範如何使用載入原始元件。

若要執行此程式碼範例,您必須提供完整元件名稱。 如需如何取得完整元件名稱的詳細資訊,請參閱 元件名稱

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 LoadRawSnippet {
   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");
   }
}
open System
open System.IO
open System.Reflection
open System.Reflection.Emit

let instantiateMyType (domain: AppDomain) =
    try
        // You must supply a valid fully qualified assembly name here.
        domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
        |> ignore  
    with e ->
        printfn $"{e.Message}"

// Loads the content of a file to a byte array.
let loadFile filename =
    use fs = new FileStream(filename, FileMode.Open)
    let buffer = Array.zeroCreate<byte> (int fs.Length)
    fs.Read(buffer, 0, buffer.Length) |> ignore
    fs.Close()
    buffer

// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
let emitAssembly (domain: AppDomain) =
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyAssembly"

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

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

    typeBuilder.CreateType() |> ignore

    assemblyBuilder.Save "temp.dll"

let myResolver (sender: obj) (args: ResolveEventArgs) =
    let domain = sender :?> AppDomain

    // Once the files are generated, this call is
    // actually no longer necessary.
    emitAssembly domain

    let rawAssembly = loadFile "temp.dll"
    let rawSymbolStore = loadFile "temp.pdb"
    domain.Load(rawAssembly, rawSymbolStore)

let currentDomain = AppDomain.CurrentDomain

instantiateMyType currentDomain   // Failed!

currentDomain.add_AssemblyResolve (ResolveEventHandler myResolver)

instantiateMyType currentDomain   // OK!
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

備註

如需此方法所有多載通用的資訊,請參閱 Load(AssemblyName) 方法多載。

從 .NET Framework 4 開始,使用此方法載入之元件的信任層級與應用程式域的信任層級相同。

適用於

Load(AssemblyName, Evidence)

警告

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.

載入提供了 AssemblyNameAssembly

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);
[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);
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
Public Function Load (assemblyRef As AssemblyName, assemblySecurity As Evidence) As Assembly

參數

assemblyRef
AssemblyName

物件,描述要載入的組件。

assemblySecurity
Evidence

用於載入組件的辨識項。

傳回

載入的組件。

實作

屬性

例外狀況

assemblyRefnull

找不到 assemblyRef

assemblyRef 不是目前載入運行時間的有效元件。

嘗試對卸載的應用程式定義域執行作業。

使用兩個不同的辨識項載入組件或模組兩次。

備註

如需此方法所有多載通用的資訊,請參閱 Load(AssemblyName) 方法多載。

適用於

Load(String, Evidence)

警告

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.

載入提供了顯示名稱的 Assembly

public:
 virtual 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);
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
Public Function Load (assemblyString As String, assemblySecurity As Evidence) As Assembly

參數

assemblyString
String

組件的顯示名稱。 請參閱 FullName

assemblySecurity
Evidence

用於載入組件的辨識項。

傳回

載入的組件。

實作

屬性

例外狀況

assemblyStringnull

找不到 assemblyString

assemblyString 不是目前載入運行時間的有效元件。

嘗試對卸載的應用程式定義域執行作業。

使用兩個不同的辨識項載入組件或模組兩次。

備註

如需這個方法所有多載通用的資訊,請參閱 Load(AssemblyName) 方法多載。

適用於

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

警告

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.

載入具備通用物件檔案格式 (COFF) 影像 (包含發出的 Assembly) 的 Assembly。 也會載入代表 Assembly 符號且未經處理的位元組。

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 (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);
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
Public Function Load (rawAssembly As Byte(), rawSymbolStore As Byte(), securityEvidence As Evidence) As Assembly

參數

rawAssembly
Byte[]

byte 類型的陣列,這是包含發出組件之以 COFF 為基礎的影像。

rawSymbolStore
Byte[]

byte 類型的陣列,包含代表組件符號的未經處理位元組。

securityEvidence
Evidence

用於載入組件的辨識項。

傳回

載入的組件。

實作

屬性

例外狀況

rawAssemblynull

rawAssembly 不是目前載入運行時間的有效元件。

嘗試對卸載的應用程式定義域執行作業。

使用兩個不同的辨識項載入組件或模組兩次。

securityEvidence 不是 null。 若未啟用舊版 CAS 原則,securityEvidence 應為 null

範例

下列範例示範如何使用載入原始元件。

若要執行此程式碼範例,您必須提供完整的元件名稱。 如需如何取得完整元件名稱的資訊,請參閱 元件名稱

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 LoadRawSnippet {
   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");
   }
}
open System
open System.IO
open System.Reflection
open System.Reflection.Emit

let instantiateMyType (domain: AppDomain) =
    try
        // You must supply a valid fully qualified assembly name here.
        domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType")
        |> ignore  
    with e ->
        printfn $"{e.Message}"

// Loads the content of a file to a byte array.
let loadFile filename =
    use fs = new FileStream(filename, FileMode.Open)
    let buffer = Array.zeroCreate<byte> (int fs.Length)
    fs.Read(buffer, 0, buffer.Length) |> ignore
    fs.Close()
    buffer

// Creates a dynamic assembly with symbol information
// and saves them to temp.dll and temp.pdb
let emitAssembly (domain: AppDomain) =
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyAssembly"

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

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

    typeBuilder.CreateType() |> ignore

    assemblyBuilder.Save "temp.dll"

let myResolver (sender: obj) (args: ResolveEventArgs) =
    let domain = sender :?> AppDomain

    // Once the files are generated, this call is
    // actually no longer necessary.
    emitAssembly domain

    let rawAssembly = loadFile "temp.dll"
    let rawSymbolStore = loadFile "temp.pdb"
    domain.Load(rawAssembly, rawSymbolStore)

let currentDomain = AppDomain.CurrentDomain

instantiateMyType currentDomain   // Failed!

currentDomain.add_AssemblyResolve (ResolveEventHandler myResolver)

instantiateMyType currentDomain   // OK!
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

備註

如需這個方法所有多載通用的資訊,請參閱 Load(AssemblyName) 方法多載。

從 .NET Framework 4 開始,使用此方法載入之元件的信任層級與應用程式域的信任層級相同。

適用於