共用方式為


AppDomain.DefineDynamicAssembly 方法

定義

在目前的應用程式定義域中定義動態組件。

多載

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean, IEnumerable<CustomAttributeBuilder>)
已淘汰.

使用指定的名稱、存取模式、儲存目錄、辨識項、權限要求、同步選項及自訂屬性來定義動態組件。

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean)
已淘汰.

使用指定的名稱、存取模式、儲存目錄、辨識項、權限要求和同步選項來定義動態組件。

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet)
已淘汰.

使用指定的名稱、存取模式、儲存目錄、辨識項和權限要求來定義動態組件。

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, PermissionSet, PermissionSet, PermissionSet)
已淘汰.

使用指定的名稱、存取模式、儲存目錄和權限要求來定義動態組件。

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence, PermissionSet, PermissionSet, PermissionSet)
已淘汰.

使用指定的名稱、存取模式、辨識項和權限要求來定義動態組件。

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

使用指定的名稱、存取模式、儲存目錄和同步處理選項來定義動態組件。

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, PermissionSet, PermissionSet, PermissionSet)
已淘汰.

使用指定的名稱、存取模式和權限要求來定義動態組件。

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence)
已淘汰.

使用指定的名稱、存取模式、儲存目錄和辨識項來定義動態組件。

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

定義動態組件,這個動態組件具有指定的名稱、存取模式和自訂模式,並且使用指定的來源做為安全性內容。

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String)

使用指定的名稱、存取模式和儲存目錄來定義動態組件。

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence)
已淘汰.

使用指定的名稱、存取模式和辨識項來定義動態組件。

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)

使用指定的名稱、存取模式及自訂屬性來定義動態組件。

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)

使用指定的名稱和存取模式定義動態組件。

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

警告

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

使用指定的名稱、存取模式、儲存目錄、辨識項、權限要求、同步選項及自訂屬性來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

將用來存取動態組件的模式。

dir
String

將儲存動態組件的目錄名稱。 如果 dirnull,就會使用目前的目錄。

evidence
Evidence

提供給動態組件的辨識項。 此辨識項的使用不變,與用於原則解析的最終辨識項集合相同。

requiredPermissions
PermissionSet

必要的權限要求。

optionalPermissions
PermissionSet

選擇性的權限要求。

refusedPermissions
PermissionSet

拒絕的權限要求。

isSynchronized
Boolean

若要在動態組件中同步建立模組、類型和成員,則為 true;否則為 false

assemblyAttributes
IEnumerable<CustomAttributeBuilder>

要套用到組件的可列舉屬性清單,如果沒有任何屬性,則是 null

傳回

使用指定名稱和功能的動態組件。

屬性

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以泛空白字元開頭,或者含有斜線或反斜線。

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

備註

使用這個方法多載指定屬性,除非在建立動態元件時套用這些屬性,否則無法正常運作。 例如,如果在建立動態元件之後新增安全性屬性,例如 SecurityTransparentAttributeSecurityCriticalAttribute 的安全性屬性無法正常運作。

只有在同時提供 參數時 evidence ,或是將動態元件儲存並重載至記憶體時,才會使用為 、 optionalPermissionsrefusedPermissions 參數指定的 requiredPermissions 許可權要求。

注意

當您開發發出動態元件的程式碼時,建議您 SecurityPermissionFlag.SkipVerificationrefusedPermissions 參數中包含 旗標。 包含此旗標可確保會驗證 Microsoft 中繼語言 (MSIL) 。 這項技術會偵測不小心產生無法驗證的程式碼,否則很難偵測。 這項技術的限制是,它也會在 SecurityException 搭配需要完全信任的程式碼使用時擲回。

定義動態 Assembly 時,只有完全信任的呼叫端可以提供辨識項。 執行時間會透過安全性原則來對應 Evidence ,以判斷授與的許可權。 部分信任的呼叫端必須為 evidence 參數提供 null 。 如果 為 evidencenull ,執行時間會將許可權集合複製到 (,也就是目前的授與和拒絕會將) 從呼叫端的元件複製到所定義的動態元件,並將原則標示為已解析。

如果動態元件儲存到磁片,後續載入會根據與動態元件儲存位置相關聯的原則取得授與。

如果 isSynchronizedtrue ,則會產生 AssemblyBuilder 的下列方法將會同步處理: DefineDynamicModuleDefineResourceAddResourceFileGetDynamicModule 、、 SetEntryPointSave 。 如果在不同的執行緒上呼叫這兩種方法,一個方法將會封鎖,直到另一個方法完成為止。

此方法多載是在 .NET Framework 3.5 中引進。

另請參閱

適用於

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

警告

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

使用指定的名稱、存取模式、儲存目錄、辨識項、權限要求和同步選項來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

將用來存取動態組件的模式。

dir
String

將儲存動態組件的目錄名稱。 如果 dirnull,目錄會預設為目前的目錄。

evidence
Evidence

提供給動態組件的辨識項。 此辨識項的使用不變,與用於原則解析的最終辨識項集合相同。

requiredPermissions
PermissionSet

必要的權限要求。

optionalPermissions
PermissionSet

選擇性的權限要求。

refusedPermissions
PermissionSet

拒絕的權限要求。

isSynchronized
Boolean

若要在動態組件中同步建立模組、類型和成員,則為 true;否則為 false

傳回

使用指定名稱和功能的動態組件。

實作

屬性

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以空白字元開頭,或者包含正斜線或反斜線。

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

範例

下列範例示範 DefineDynamicAssembly 方法和 AssemblyResolve 事件。

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

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

   }

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

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

};

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

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

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

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

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

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

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

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

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

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}
open System
open System.Reflection
open System.Reflection.Emit

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

let defineDynamicAssembly (domain: AppDomain) =
    // Build a dynamic assembly using Reflection Emit API.
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyDynamicAssembly"

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

    ilGenerator.EmitWriteLine "MyDynamicType instantiated!"
    ilGenerator.Emit OpCodes.Ret

    typeBuilder.CreateType() |> ignore

    assemblyBuilder

let myResolveEventHandler (sender: obj) _ =
    defineDynamicAssembly (sender :?> AppDomain)
    :> Assembly
   
let currentDomain = AppDomain.CurrentDomain

instantiateMyDynamicType currentDomain   // Failed!

currentDomain.add_AssemblyResolve(ResolveEventHandler myResolveEventHandler)

instantiateMyDynamicType currentDomain   // OK!

Imports System.Reflection
Imports System.Reflection.Emit

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

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

End Module 'Test

備註

只有在也提供 時 evidence ,或是將動態元件儲存並重載至記憶體時,才會使用為 requiredPermissionsoptionalPermissionsrefusedPermissions 指定的許可權要求。

注意

在開發發出動態元件的程式碼期間,建議您在 中包含 SecurityPermissionFlag.SkipVerificationrefusedPermissions 。 在 SkipVerification 參數中包含 refusedPermissions 可確保 MSIL 已驗證。 這項技術的限制是,它也會在 SecurityException 搭配需要完全信任的程式碼使用時擲回。

定義動態 Assembly 時,只有完全信任的呼叫端可以提供其辨識項。 執行時間會透過安全性原則對應 Evidence ,以判斷授與的許可權。 部分信任的呼叫端必須為 evidence 參數提供 null 。 如果 evidencenull ,則執行時間會將許可權集合,也就是目前的授與和拒絕集合從呼叫端 Assembly 的 複製到要定義的動態 Assembly ,並將原則標示為已解析。

如果動態 Assembly 儲存到磁片,後續載入會根據與儲存 位置 Assembly 相關聯的原則來取得授與。

如果 isSynchronizedtrue ,則會產生 AssemblyBuilder 的下列方法將會同步處理: DefineDynamicModuleDefineResourceAddResourceFileGetDynamicModule 、、 SetEntryPointSave 。 如果在不同的執行緒上呼叫這兩種方法,一個方法會封鎖,直到其他執行緒完成為止。

適用於

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

警告

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

使用指定的名稱、存取模式、儲存目錄、辨識項和權限要求來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

將用來存取動態組件的模式。

dir
String

將儲存組件的目錄名稱。 如果 dirnull,目錄會預設為目前的目錄。

evidence
Evidence

提供給動態組件的辨識項。 此辨識項的使用不變,與用於原則解析的最終辨識項集合相同。

requiredPermissions
PermissionSet

必要的權限要求。

optionalPermissions
PermissionSet

選擇性的權限要求。

refusedPermissions
PermissionSet

拒絕的權限要求。

傳回

使用指定名稱和功能的動態組件。

實作

屬性

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以空白字元開頭,或者包含正斜線或反斜線。

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

範例

下列範例示範 DefineDynamicAssembly 方法和 AssemblyResolve 事件。

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

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

   }

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

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

};

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

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

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

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

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

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

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

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

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

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}
open System
open System.Reflection
open System.Reflection.Emit

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

let defineDynamicAssembly (domain: AppDomain) =
    // Build a dynamic assembly using Reflection Emit API.
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyDynamicAssembly"

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

    ilGenerator.EmitWriteLine "MyDynamicType instantiated!"
    ilGenerator.Emit OpCodes.Ret

    typeBuilder.CreateType() |> ignore

    assemblyBuilder

let myResolveEventHandler (sender: obj) _ =
    defineDynamicAssembly (sender :?> AppDomain)
    :> Assembly
   
let currentDomain = AppDomain.CurrentDomain

instantiateMyDynamicType currentDomain   // Failed!

currentDomain.add_AssemblyResolve(ResolveEventHandler myResolveEventHandler)

instantiateMyDynamicType currentDomain   // OK!

Imports System.Reflection
Imports System.Reflection.Emit

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

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

End Module 'Test

備註

指定給 requiredPermissionsoptionalPermissionsrefusedPermissions 的許可權要求只有在也提供時 evidence ,或是將動態元件儲存並重載到記憶體時才會使用。

注意

在開發發出動態元件的程式碼期間,建議您在 SecurityPermissionFlag.SkipVerification 中包含 refusedPermissions 。 在 SkipVerification 參數中包含 refusedPermissions 可確保 MSIL 已驗證。 這項技術的限制是,當搭配需要完全信任的程式碼使用時,也會 SecurityException 擲回。

定義動態 Assembly 時,只有完全信任的呼叫端才能提供它們 evidence 。 執行時間會 Evidence 透過安全性原則對應 ,以判斷授與的許可權。 部分信任的呼叫端必須提供 Null evidence 。 如果 為 evidencenull ,執行時間會將許可權集合,也就是目前的授與和拒絕集從呼叫端 Assembly 複製到要定義的動態 Assembly ,並將原則標示為已解析。

如果動態 Assembly 儲存至磁片,後續載入將會根據與儲存位置相關聯的原則 Assembly 來獲得授與。

這個方法應該只用來定義目前應用程式域中的動態元件。 如需詳細資訊,請參閱 Load(AssemblyName) 方法多載。

適用於

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

警告

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

使用指定的名稱、存取模式、儲存目錄和權限要求來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

將用來存取動態組件的模式。

dir
String

將儲存組件的目錄名稱。 如果 dirnull,目錄會預設為目前的目錄。

requiredPermissions
PermissionSet

必要的權限要求。

optionalPermissions
PermissionSet

選擇性的權限要求。

refusedPermissions
PermissionSet

拒絕的權限要求。

傳回

使用指定名稱和功能的動態組件。

實作

屬性

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以空白字元開頭,或者包含正斜線或反斜線。

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

範例

下列範例示範 DefineDynamicAssembly 方法和 AssemblyResolve 事件。

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

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

   }

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

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

};

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

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

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

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

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

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

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

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

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

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}
open System
open System.Reflection
open System.Reflection.Emit

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

let defineDynamicAssembly (domain: AppDomain) =
    // Build a dynamic assembly using Reflection Emit API.
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyDynamicAssembly"

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

    ilGenerator.EmitWriteLine "MyDynamicType instantiated!"
    ilGenerator.Emit OpCodes.Ret

    typeBuilder.CreateType() |> ignore

    assemblyBuilder

let myResolveEventHandler (sender: obj) _ =
    defineDynamicAssembly (sender :?> AppDomain)
    :> Assembly
   
let currentDomain = AppDomain.CurrentDomain

instantiateMyDynamicType currentDomain   // Failed!

currentDomain.add_AssemblyResolve(ResolveEventHandler myResolveEventHandler)

instantiateMyDynamicType currentDomain   // OK!

Imports System.Reflection
Imports System.Reflection.Emit

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

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

End Module 'Test

備註

除非動態元件已儲存並重載記憶體,否則不會使用 針對 、 optionalPermissionsrefusedPermissions 指定的 requiredPermissions 許可權要求。 若要指定永不儲存至磁片之暫時性元件的許可權要求,請使用 方法的多 DefineDynamicAssembly 載,指定辨識項和要求的許可權,並提供 Evidence 物件。

注意

在開發發出動態元件的程式碼期間,建議您使用方法的多 DefineDynamicAssembly 載來指定辨識項和許可權、提供您想要動態元件擁有的辨識項,並在 SecurityPermissionFlag.SkipVerification 中包含 refusedPermissions 。 在 SkipVerification 參數中包含 refusedPermissions 可確保 MSIL 已驗證。 這項技術的限制是,當搭配需要完全信任的程式碼使用時,也會 SecurityException 擲回。

這個方法應該只用來定義目前應用程式域中的動態元件。 如需詳細資訊,請參閱 Load(AssemblyName) 方法多載。

適用於

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

警告

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

使用指定的名稱、存取模式、辨識項和權限要求來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

將用來存取動態組件的模式。

evidence
Evidence

提供給動態組件的辨識項。 此辨識項的使用不變,與用於原則解析的最終辨識項集合相同。

requiredPermissions
PermissionSet

必要的權限要求。

optionalPermissions
PermissionSet

選擇性的權限要求。

refusedPermissions
PermissionSet

拒絕的權限要求。

傳回

使用指定名稱和功能的動態組件。

實作

屬性

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以空白字元開頭,或者包含正斜線或反斜線。

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

範例

下列範例示範 DefineDynamicAssembly 方法和 AssemblyResolve 事件。

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

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

   }

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

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

};

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

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

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

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

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

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

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

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

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

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}
open System
open System.Reflection
open System.Reflection.Emit

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

let defineDynamicAssembly (domain: AppDomain) =
    // Build a dynamic assembly using Reflection Emit API.
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyDynamicAssembly"

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

    ilGenerator.EmitWriteLine "MyDynamicType instantiated!"
    ilGenerator.Emit OpCodes.Ret

    typeBuilder.CreateType() |> ignore

    assemblyBuilder

let myResolveEventHandler (sender: obj) _ =
    defineDynamicAssembly (sender :?> AppDomain)
    :> Assembly
   
let currentDomain = AppDomain.CurrentDomain

instantiateMyDynamicType currentDomain   // Failed!

currentDomain.add_AssemblyResolve(ResolveEventHandler myResolveEventHandler)

instantiateMyDynamicType currentDomain   // OK!

Imports System.Reflection
Imports System.Reflection.Emit

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

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

End Module 'Test

備註

指定給 requiredPermissionsoptionalPermissionsrefusedPermissions 的許可權要求只有在也提供時 evidence ,或是將動態元件儲存並重載到記憶體時才會使用。

注意

在開發發出動態元件的程式碼期間,建議您在 SecurityPermissionFlag.SkipVerification 中包含 refusedPermissions 。 在 SkipVerification 參數中包含 refusedPermissions 可確保 MSIL 已驗證。 這項技術的限制是,當搭配需要完全信任的程式碼使用時,也會 SecurityException 擲回。

定義動態 Assembly 時,只有完全信任的呼叫端才能提供它們 evidence 。 執行時間會 Evidence 透過安全性原則對應 ,以判斷授與的許可權。 部分信任的呼叫端必須提供 Null evidence 。 如果 為 evidencenull ,執行時間會將許可權集合,也就是目前的授與和拒絕集從呼叫端 Assembly 複製到要定義的動態 Assembly ,並將原則標示為已解析。

如果動態 Assembly 儲存至磁片,後續載入將會根據與儲存位置相關聯的原則 Assembly 來獲得授與。

這個方法應該只用來定義目前應用程式域中的動態元件。 如需詳細資訊,請參閱 Load(AssemblyName) 方法多載。

適用於

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

使用指定的名稱、存取模式、儲存目錄和同步處理選項來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

將用來存取動態組件的模式。

dir
String

將儲存動態組件的目錄名稱。 如果 dirnull,就會使用目前的目錄。

isSynchronized
Boolean

若要在動態組件中同步建立模組、類型和成員,則為 true;否則為 false

assemblyAttributes
IEnumerable<CustomAttributeBuilder>

要套用到組件的可列舉屬性清單,如果沒有任何屬性,則是 null

傳回

使用指定名稱和功能的動態組件。

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以泛空白字元開頭,或者含有斜線或反斜線。

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

備註

使用這個方法多載來指定屬性,除非在建立動態元件時套用它們,否則無法正確運作。 例如,如果在建立動態元件之後新增,例如 和 SecurityCriticalAttribute 之類的 SecurityTransparentAttribute 安全性屬性將無法正常運作。

如果 isSynchronizedtrue ,產生的 AssemblyBuilder 下列方法將會同步處理: DefineDynamicModuleDefineResource 、、 AddResourceFileGetDynamicModule 、、 SetEntryPointSave 。 如果在不同的執行緒上呼叫這兩種方法,一個方法將會封鎖,直到另一個方法完成為止。

另請參閱

適用於

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

警告

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

使用指定的名稱、存取模式和權限要求來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

將用來存取動態組件的模式。

requiredPermissions
PermissionSet

必要的權限要求。

optionalPermissions
PermissionSet

選擇性的權限要求。

refusedPermissions
PermissionSet

拒絕的權限要求。

傳回

使用指定名稱和功能的動態組件。

實作

屬性

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以空白字元開頭,或者包含正斜線或反斜線。

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

範例

下列範例示範 DefineDynamicAssembly 方法和 AssemblyResolve 事件。

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

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

   }

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

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

};

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

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

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

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

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

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

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

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

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

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}
open System
open System.Reflection
open System.Reflection.Emit

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

let defineDynamicAssembly (domain: AppDomain) =
    // Build a dynamic assembly using Reflection Emit API.
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyDynamicAssembly"

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

    ilGenerator.EmitWriteLine "MyDynamicType instantiated!"
    ilGenerator.Emit OpCodes.Ret

    typeBuilder.CreateType() |> ignore

    assemblyBuilder

let myResolveEventHandler (sender: obj) _ =
    defineDynamicAssembly (sender :?> AppDomain)
    :> Assembly
   
let currentDomain = AppDomain.CurrentDomain

instantiateMyDynamicType currentDomain   // Failed!

currentDomain.add_AssemblyResolve(ResolveEventHandler myResolveEventHandler)

instantiateMyDynamicType currentDomain   // OK!

Imports System.Reflection
Imports System.Reflection.Emit

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

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

End Module 'Test

備註

除非已儲存動態元件並重載到記憶體中,否則不會使用為 requiredPermissionsoptionalPermissionsrefusedPermissions 指定的許可權要求。 若要指定永不儲存至磁片之暫時性元件的許可權要求,請使用 方法的多 DefineDynamicAssembly 載來指定辨識項和要求的許可權,並提供 Evidence 物件。

注意

在開發發出動態元件的程式碼期間,建議您使用 指定辨識項和許可權的方法多載 DefineDynamicAssembly 、提供您想要動態元件擁有的辨識項,並在 SecurityPermissionFlag.SkipVerification 中包含 refusedPermissions 。 在 SkipVerification 參數中包含 refusedPermissions 可確保 MSIL 已驗證。 這項技術的限制是,它也會在 SecurityException 搭配需要完全信任的程式碼使用時擲回。

這個方法應該只用來定義目前應用程式域中的動態元件。 如需詳細資訊,請參閱 Load(AssemblyName) 方法多載 。

適用於

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

使用指定的名稱、存取模式、儲存目錄和辨識項來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

將用來存取動態組件的模式。

dir
String

將儲存組件的目錄名稱。 如果 dirnull,目錄會預設為目前的目錄。

evidence
Evidence

提供給動態組件的辨識項。 此辨識項的使用不變,與用於原則解析的最終辨識項集合相同。

傳回

使用指定名稱和功能的動態組件。

實作

屬性

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以空白字元開頭,或者包含正斜線或反斜線。

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

範例

下列範例示範 DefineDynamicAssembly 方法和 AssemblyResolve 事件。

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

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

   }

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

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

};

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

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

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

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

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

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

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

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

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

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}
open System
open System.Reflection
open System.Reflection.Emit

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

let defineDynamicAssembly (domain: AppDomain) =
    // Build a dynamic assembly using Reflection Emit API.
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyDynamicAssembly"

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

    ilGenerator.EmitWriteLine "MyDynamicType instantiated!"
    ilGenerator.Emit OpCodes.Ret

    typeBuilder.CreateType() |> ignore

    assemblyBuilder

let myResolveEventHandler (sender: obj) _ =
    defineDynamicAssembly (sender :?> AppDomain)
    :> Assembly
   
let currentDomain = AppDomain.CurrentDomain

instantiateMyDynamicType currentDomain   // Failed!

currentDomain.add_AssemblyResolve(ResolveEventHandler myResolveEventHandler)

instantiateMyDynamicType currentDomain   // OK!

Imports System.Reflection
Imports System.Reflection.Emit

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

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

End Module 'Test

備註

定義動態 Assembly 時,只有完全信任的呼叫端可以提供其 evidence 。 執行時間會透過安全性原則對應 Evidence ,以判斷授與的許可權。 部分信任的呼叫端必須提供 Null evidence 。 如果 evidencenull ,則執行時間會將許可權集合,也就是目前的授與和拒絕集合從呼叫端 Assembly 的 複製到要定義的動態 Assembly ,並將原則標示為已解析。

如果動態 Assembly 儲存到磁片,後續載入會根據與儲存 位置 Assembly 相關聯的原則來取得授與。

這個方法應該只用來定義目前應用程式域中的動態元件。 如需詳細資訊,請參閱 Load(AssemblyName) 方法多載。

注意

在開發發出動態元件的程式碼期間,建議您使用 指定辨識項和許可權的方法多載 DefineDynamicAssembly 、提供您想要動態元件擁有的辨識項,並在 SecurityPermissionFlag.SkipVerification 中包含 refusedPermissions 。 在 SkipVerification 參數中包含 refusedPermissions 可確保 MSIL 已驗證。 這項技術的限制是,它也會在 SecurityException 搭配需要完全信任的程式碼使用時擲回。

適用於

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

定義動態組件,這個動態組件具有指定的名稱、存取模式和自訂模式,並且使用指定的來源做為安全性內容。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

提供給動態組件的存取模式。

assemblyAttributes
IEnumerable<CustomAttributeBuilder>

要套用到組件的可列舉屬性清單,如果沒有任何屬性,則是 null

securityContextSource
SecurityContextSource

安全性內容的來源。

傳回

使用指定名稱和功能的動態組件。

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以泛空白字元開頭,或者含有斜線或反斜線。

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

securityContextSource 的值不是其中一個列舉值。

備註

使用這個方法多載指定屬性,除非在建立動態元件時套用這些屬性,否則無法正常運作。 例如,如果在建立動態元件之後新增安全性屬性,例如 SecurityTransparentAttributeSecurityCriticalAttribute 的安全性屬性無法正常運作。

這個方法應該只用來定義目前應用程式域中的動態元件。 如需此限制的詳細資訊,請參閱 Load(AssemblyName) 方法多載。

適用於

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String)

使用指定的名稱、存取模式和儲存目錄來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

將用來存取動態組件的模式。

dir
String

將儲存組件的目錄名稱。 如果 dirnull,目錄會預設為目前的目錄。

傳回

使用指定名稱和功能的動態組件。

實作

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以空白字元開頭,或者包含正斜線或反斜線。

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

範例

下列範例示範 DefineDynamicAssembly 方法和 AssemblyResolve 事件。

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

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

   }

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

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

};

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

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

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

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

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

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

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

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

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

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}
open System
open System.Reflection
open System.Reflection.Emit

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

let defineDynamicAssembly (domain: AppDomain) =
    // Build a dynamic assembly using Reflection Emit API.
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyDynamicAssembly"

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

    ilGenerator.EmitWriteLine "MyDynamicType instantiated!"
    ilGenerator.Emit OpCodes.Ret

    typeBuilder.CreateType() |> ignore

    assemblyBuilder

let myResolveEventHandler (sender: obj) _ =
    defineDynamicAssembly (sender :?> AppDomain)
    :> Assembly
   
let currentDomain = AppDomain.CurrentDomain

instantiateMyDynamicType currentDomain   // Failed!

currentDomain.add_AssemblyResolve(ResolveEventHandler myResolveEventHandler)

instantiateMyDynamicType currentDomain   // OK!

Imports System.Reflection
Imports System.Reflection.Emit

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

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

End Module 'Test

備註

這個方法應該只用來定義目前應用程式域中的動態元件。 如需詳細資訊,請參閱 Load(AssemblyName) 方法多載。

注意

在開發發出動態元件的程式碼期間,建議您使用 指定辨識項和許可權的方法多載 DefineDynamicAssembly 、提供您想要動態元件擁有的辨識項,並在 SecurityPermissionFlag.SkipVerification 中包含 refusedPermissions 。 在 SkipVerification 參數中包含 refusedPermissions 可確保 MSIL 已驗證。 這項技術的限制是,它也會在 SecurityException 搭配需要完全信任的程式碼使用時擲回。

適用於

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence)

警告

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

使用指定的名稱、存取模式和辨識項來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

將用來存取動態組件的模式。

evidence
Evidence

提供給動態組件的辨識項。 此辨識項的使用不變,與用於原則解析的最終辨識項集合相同。

傳回

使用指定名稱和功能的動態組件。

實作

屬性

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以空白字元開頭,或者包含正斜線或反斜線。

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

範例

下列範例示範 DefineDynamicAssembly 方法和 AssemblyResolve 事件。

首先,程式碼範例會嘗試呼叫 CreateInstance 具有無效元件名稱的 方法來建立 的 MyDynamicType 實例,並攔截產生的例外狀況。

然後,程式碼範例會新增 事件的事件處理常式 AssemblyResolve ,然後再次嘗試建立 的 MyDynamicType 實例。 在呼叫 CreateInstance 期間, AssemblyResolve 會針對不正確元件引發 事件。 事件處理常式會建立包含名為 MyDynamicType 的型別的動態元件,提供無參數建構函式類型,並傳回新的動態元件。 CreateInstance接著呼叫 會順利完成,而 的 MyDynamicType 建構函式會在主控台顯示訊息。

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

   }

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

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

};

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

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

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

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

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

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

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

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

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

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}
open System
open System.Reflection
open System.Reflection.Emit

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

let defineDynamicAssembly (domain: AppDomain) =
    // Build a dynamic assembly using Reflection Emit API.
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyDynamicAssembly"

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

    ilGenerator.EmitWriteLine "MyDynamicType instantiated!"
    ilGenerator.Emit OpCodes.Ret

    typeBuilder.CreateType() |> ignore

    assemblyBuilder

let myResolveEventHandler (sender: obj) _ =
    defineDynamicAssembly (sender :?> AppDomain)
    :> Assembly
   
let currentDomain = AppDomain.CurrentDomain

instantiateMyDynamicType currentDomain   // Failed!

currentDomain.add_AssemblyResolve(ResolveEventHandler myResolveEventHandler)

instantiateMyDynamicType currentDomain   // OK!

Imports System.Reflection
Imports System.Reflection.Emit

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

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

End Module 'Test

備註

定義動態 Assembly 時,只有完全信任的呼叫端才能提供它們 evidence 。 執行時間會 Evidence 透過安全性原則對應 ,以判斷授與的許可權。 部分信任的呼叫端必須提供 Null evidence 。 如果 為 evidencenull ,執行時間會將許可權集合,也就是目前的授與和拒絕集從呼叫端 Assembly 複製到要定義的動態 Assembly ,並將原則標示為已解析。

如果動態 Assembly 儲存至磁片,後續載入將會根據與儲存位置相關聯的原則 Assembly 來獲得授與。

這個方法應該只用來定義目前應用程式域中的動態元件。 如需詳細資訊,請參閱 Load(AssemblyName) 方法多載。

注意

在開發發出動態元件的程式碼期間,建議您使用方法的多 DefineDynamicAssembly 載來指定辨識項和許可權、提供您想要動態元件擁有的辨識項,並在 SecurityPermissionFlag.SkipVerification 中包含 refusedPermissions 。 在 SkipVerification 參數中包含 refusedPermissions 可確保 MSIL 已驗證。 這項技術的限制是,當搭配需要完全信任的程式碼使用時,也會 SecurityException 擲回。

適用於

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)

使用指定的名稱、存取模式及自訂屬性來定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

提供給動態組件的存取模式。

assemblyAttributes
IEnumerable<CustomAttributeBuilder>

要套用到組件的可列舉屬性清單,如果沒有任何屬性,則是 null

傳回

使用指定名稱和功能的動態組件。

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以泛空白字元開頭,或者含有斜線或反斜線。

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

範例

下列程式碼範例示範如何建立具有 的 SecurityTransparentAttribute 動態元件。 屬性必須指定為 物件的陣列專案 CustomAttributeBuilder

建立 CustomAttributeBuilder 的第一個步驟是取得 屬性的建構函式。 建構函式沒有參數,因此 GetConstructor 會以空的 Type 物件陣列呼叫 方法,以表示參數的類型。 第二個步驟是將產生的 ConstructorInfo 物件傳遞至 類別的 CustomAttributeBuilder 建構函式,以及型 Object 別的空陣列來表示引數。

CustomAttributeBuilder結果接著會傳遞至 DefineDynamicAssembly 方法做為陣列的唯一元素。

範例程式碼會在新的動態元件中定義模組和類型,然後顯示元件的屬性。

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

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

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

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

/* This code example produces the following output:

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

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

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

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

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

/* This code example produces the following output:

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

// Create a CustomAttributeBuilder for the assembly attribute.
//
// SecurityTransparentAttribute has a parameterless constructor,
// which is retrieved by passing an array of empty types for the
// constructor's parameter types. The CustomAttributeBuilder is
// then created by passing the ConstructorInfo and an empty array
// of objects to represent the parameters.
//
let transparentCtor =
    typeof<SecurityTransparentAttribute>.GetConstructor(Type.EmptyTypes)
let transparent = CustomAttributeBuilder(transparentCtor, [||])

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

let mb = ab.DefineDynamicModule aName.Name
let tb = mb.DefineType(
    "MyDynamicType",
    TypeAttributes.Public )
tb.CreateType() |> ignore

printfn $"{ab}\nAssembly attributes:"
for attr in ab.GetCustomAttributes true do
    printfn $"\t{attr}"

(* This code example produces the following output:

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

Module Example

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

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

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

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

備註

使用這個方法多載來指定屬性,除非在建立動態元件時套用它們,否則無法正確運作。 例如,如果在建立動態元件之後新增,例如 和 SecurityCriticalAttribute 之類的 SecurityTransparentAttribute 安全性屬性將無法正常運作。

這個方法應該只用來定義目前應用程式域中的動態元件。 如需此限制的詳細資訊,請參閱 Load(AssemblyName) 方法多載。

此方法多載會在 .NET Framework 3.5 中引進。

另請參閱

適用於

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)

使用指定的名稱和存取模式定義動態組件。

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

參數

name
AssemblyName

動態組件的唯一識別。

access
AssemblyBuilderAccess

提供給動態組件的存取模式。

傳回

使用指定名稱和存取模式的動態組件。

實作

例外狀況

namenull

nameName 屬性為 null

-或-

nameName 屬性以空白字元開頭,或者包含正斜線或反斜線。

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

範例

下列範例示範 DefineDynamicAssembly 方法和 AssemblyResolve 事件。

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

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

   }

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

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

};

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

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

      InstantiateMyDynamicType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);   // OK!
   }

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

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

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

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

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

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

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}
open System
open System.Reflection
open System.Reflection.Emit

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

let defineDynamicAssembly (domain: AppDomain) =
    // Build a dynamic assembly using Reflection Emit API.
    let assemblyName = AssemblyName()
    assemblyName.Name <- "MyDynamicAssembly"

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

    ilGenerator.EmitWriteLine "MyDynamicType instantiated!"
    ilGenerator.Emit OpCodes.Ret

    typeBuilder.CreateType() |> ignore

    assemblyBuilder

let myResolveEventHandler (sender: obj) _ =
    defineDynamicAssembly (sender :?> AppDomain)
    :> Assembly
   
let currentDomain = AppDomain.CurrentDomain

instantiateMyDynamicType currentDomain   // Failed!

currentDomain.add_AssemblyResolve(ResolveEventHandler myResolveEventHandler)

instantiateMyDynamicType currentDomain   // OK!

Imports System.Reflection
Imports System.Reflection.Emit

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

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

End Module 'Test

備註

這個方法應該只用來定義目前應用程式域中的動態元件。 如需詳細資訊,請參閱 Load(AssemblyName) 方法多載。

注意

在開發發出動態元件的程式碼期間,建議您使用方法的多 DefineDynamicAssembly 載來指定辨識項和許可權、提供您想要動態元件擁有的辨識項,並在 SecurityPermissionFlag.SkipVerification 中包含 refusedPermissions 。 在 SkipVerification 參數中包含 refusedPermissions 可確保 MSIL 已驗證。 這項技術的限制是,當搭配需要完全信任的程式碼使用時,也會 SecurityException 擲回。

適用於