AppDomain.CreateInstanceFrom 方法

定义

创建在指定程序集文件中定义的指定类型的新实例。Creates a new instance of a specified type defined in the specified assembly file.

重载

CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

创建在指定程序集文件中定义的指定类型的新实例。Creates a new instance of the specified type defined in the specified assembly file.

CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

创建在指定程序集文件中定义的指定类型的新实例。Creates a new instance of the specified type defined in the specified assembly file.

CreateInstanceFrom(String, String, Object[])

创建在指定程序集文件中定义的指定类型的新实例。Creates a new instance of the specified type defined in the specified assembly file.

CreateInstanceFrom(String, String)

创建在指定程序集文件中定义的指定类型的新实例。Creates a new instance of the specified type defined in the specified assembly file.

CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

警告

此 API 现已过时。

创建在指定程序集文件中定义的指定类型的新实例。Creates a new instance of the specified type defined in the specified assembly file.

public:
 System::Runtime::Remoting::ObjectHandle ^ CreateInstanceFrom(System::String ^ assemblyFile, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes, System::Security::Policy::Evidence ^ securityAttributes);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
[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 CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityAttributes);
member this.CreateInstanceFrom : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle

参数

assemblyFile
String

文件的名称(包括路径),该文件包含定义所请求类型的程序集。The name, including the path, of a file that contains an assembly that defines the requested type. 该程序集是使用 LoadFrom(String) 方法加载的。The assembly is loaded using the LoadFrom(String) method.

typeName
String

FullName 属性返回的所请求类型的完全限定名称,包含命名空间而不是程序集。The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

ignoreCase
Boolean

一个布尔值,指示是否执行区分大小写的搜索。A Boolean value specifying whether to perform a case-sensitive search or not.

bindingAttr
BindingFlags

影响 typeName 构造函数搜索的零个或多个位标志的组合。A combination of zero or more bit flags that affect the search for the typeName constructor. 如果 bindingAttr 为零,则对公共构造函数进行区分大小写的搜索。If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

一个对象,它启用绑定、对参数类型的强制、对成员的调用,以及通过反射对 MemberInfo 对象的检索。An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects through reflection. 如果 binder 为 null,则使用默认联编程序。If binder is null, the default binder is used.

args
Object[]

要传递给构造函数的实参。The arguments to pass to the constructor. 此实参数组必须在数量、顺序和类型方面与要调用的构造函数的形参匹配。This array of arguments must match in number, order, and type the parameters of the constructor to invoke. 如果无参数构造函数是首选,则 args 必须为空数组或 NULL。If the parameterless constructor is preferred, args must be an empty array or null.

culture
CultureInfo

区域性特定的信息,这些信息控制将 args 强制转换为 typeName 构造函数所声明的正式类型。Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. 如果 culturenull,则使用当前线程的 CultureInfoIf culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

可参与激活的一个或多个属性的数组。An array of one or more attributes that can participate in activation. 通常,为包含单个 UrlAttribute 对象的数组,该对象指定激活远程对象所需的 URL。Typically, an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

此参数与客户端激活的对象相关。This parameter is related to client-activated objects. 客户端激活是一项传统技术,保留用于向后兼容,但不建议用于新的开发。Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. 应改用 Windows Communication Foundation 来开发分布式应用程序。Distributed applications should instead use Windows Communication Foundation.

securityAttributes
Evidence

用于授权创建 typeName 的信息。Information used to authorize creation of typeName.

返回

一个对象,它是新实例的包装,或者如果找不到 null,则为 typeNameAn object that is a wrapper for the new instance, or null if typeName is not found. 返回值需要打开包装才能访问真实对象。The return value needs to be unwrapped to access the real object.

实现

属性

异常

assemblyFilenullassemblyFile is null.

- 或 --or- typeNamenulltypeName is null.

调用方不能为非继承自 MarshalByRefObject 的对象提供激活属性。The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.

- 或 --or- securityAttributes 不是 nullsecurityAttributes is not null. 未启用旧版 CAS 策略时,securityAttributes 应为 nullWhen legacy CAS policy is not enabled, securityAttributes should be null.

在卸载的应用程序域上尝试该操作。The operation is attempted on an unloaded application domain.

未找到 assemblyFileassemblyFile was not found.

typeName 中未找到 assemblyFiletypeName was not found in assemblyFile.

未找到匹配的公共构造函数。No matching public constructor was found.

调用方没有足够的权限调用此构造函数。The caller does not have sufficient permission to call this constructor.

assemblyFile 不是有效的程序集。assemblyFile is not a valid assembly.

- 或 --or- 当前加载的是公共语言运行时 2.0 版或更高版本,而 assemblyFile 是用更高版本编译的。Version 2.0 or later of the common language runtime is currently loaded and assemblyFile was compiled with a later version.

一个程序集或模块用两个不同的证据加载了两次。An assembly or module was loaded twice with two different evidences.

此示例为 nullThis instance is null.

注解

有关此方法的详细信息,请参阅 Activator.CreateInstanceFrom 方法。For more information about this method, see the Activator.CreateInstanceFrom method.

如果使用 CreateInstanceFrom 方法来创建目标应用程序域中的实例,而不是调用的应用程序域,则会在目标应用程序域中加载该程序集。When the CreateInstanceFrom method is used to create an instance in a target application domain, other than the application domain from which the call is made, the assembly is loaded in the target application domain. 但是,如果实例在调用应用程序域中解包,则以特定方式使用已解包的实例可能会导致程序集加载到调用应用程序域中。However, if the instance is unwrapped in the calling application domain, using the unwrapped instance in certain ways can cause the assembly to be loaded into the calling application domain. 例如,在实例解包后,可能会请求其类型信息,以便以后调用其方法。For example, after the instance is unwrapped, its type information might be requested, in order to call its methods late-bound. 将程序集加载到调用应用程序域时,可能会出现异常。When the assembly is loaded into the calling application domain, exceptions can occur.

  • 如果以前将同一程序集的另一个版本加载到调用应用程序域中,或调用应用程序域的加载路径不同于目标应用程序域的加载路径,则可能会发生诸如 MissingMethodException 的异常。If another version of the same assembly was previously loaded into the calling application domain, or if the load path of the calling application domain is different from that of the target application domain, exceptions such as MissingMethodException can occur.

  • 如果调用应用程序域对实例类型进行早期绑定调用,则当尝试强制转换实例时,可能会引发 InvalidCastExceptionIf the calling application domain makes early-bound calls to the instance type, InvalidCastException can be thrown when an attempt is made to cast the instance.

安全性

FileIOPermissionAccess
用于读取包含程序集清单的文件。for the ability to read the file containing the assembly manifest. 关联的枚举: ReadAssociated enumeration: Read

WebPermission
如果程序集不是本地的,则能够访问程序集的位置。for the ability to access the location of the assembly if the assembly is not local.

SecurityPermission
提供证据。to provide evidence. 关联的枚举:ControlEvidenceAssociated enumeration: ControlEvidence.

另请参阅

CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

创建在指定程序集文件中定义的指定类型的新实例。Creates a new instance of the specified type defined in the specified assembly file.

public:
 System::Runtime::Remoting::ObjectHandle ^ CreateInstanceFrom(System::String ^ assemblyFile, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes);
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
member this.CreateInstanceFrom : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> System.Runtime.Remoting.ObjectHandle

参数

assemblyFile
String

文件的名称(包括路径),该文件包含定义所请求类型的程序集。The name, including the path, of a file that contains an assembly that defines the requested type. 该程序集是使用 LoadFrom(String) 方法加载的。The assembly is loaded using the LoadFrom(String) method.

typeName
String

FullName 属性返回的所请求类型的完全限定名称,包含命名空间而不是程序集。The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

ignoreCase
Boolean

一个布尔值,指示是否执行区分大小写的搜索。A Boolean value specifying whether to perform a case-sensitive search or not.

bindingAttr
BindingFlags

影响 typeName 构造函数搜索的零个或多个位标志的组合。A combination of zero or more bit flags that affect the search for the typeName constructor. 如果 bindingAttr 为零,则对公共构造函数进行区分大小写的搜索。If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

一个对象,它启用绑定、对参数类型的强制、对成员的调用,以及通过反射对 MemberInfo 对象的检索。An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects through reflection. 如果 binder 为 null,则使用默认联编程序。If binder is null, the default binder is used.

args
Object[]

要传递给构造函数的实参。The arguments to pass to the constructor. 此实参数组必须在数量、顺序和类型方面与要调用的构造函数的形参匹配。This array of arguments must match in number, order, and type the parameters of the constructor to invoke. 如果无参数构造函数是首选,则 args 必须为空数组或 NULL。If the parameterless constructor is preferred, args must be an empty array or null.

culture
CultureInfo

区域性特定的信息,这些信息控制将 args 强制转换为 typeName 构造函数所声明的正式类型。Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. 如果 culturenull,则使用当前线程的 CultureInfoIf culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

可参与激活的一个或多个属性的数组。An array of one or more attributes that can participate in activation. 通常,为包含单个 UrlAttribute 对象的数组,该对象指定激活远程对象所需的 URL。Typically, an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

此参数与客户端激活的对象相关。This parameter is related to client-activated objects. 客户端激活是一项传统技术,保留用于向后兼容,但不建议用于新的开发。Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. 应改用 Windows Communication Foundation 来开发分布式应用程序。Distributed applications should instead use Windows Communication Foundation.

返回

一个对象,它是新实例的包装,或者如果找不到 null,则为 typeNameAn object that is a wrapper for the new instance, or null if typeName is not found. 返回值需要打开包装才能访问真实对象。The return value needs to be unwrapped to access the real object.

异常

assemblyFilenullassemblyFile is null.

- 或 --or- typeNamenulltypeName is null.

调用方不能为非继承自 MarshalByRefObject 的对象提供激活属性。The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.

在卸载的应用程序域上尝试该操作。The operation is attempted on an unloaded application domain.

未找到 assemblyFileassemblyFile was not found.

typeName 中未找到 assemblyFiletypeName was not found in assemblyFile.

未找到匹配的公共构造函数。No matching public constructor was found.

调用方没有足够的权限调用此构造函数。The caller does not have sufficient permission to call this constructor.

assemblyFile 不是有效的程序集。assemblyFile is not a valid assembly.

- 或 --or- assemblyFile 使用高于当前所加载版本的公共语言运行时版本编译而成。assemblyFile was compiled with a later version of the common language runtime than the version that is currently loaded.

一个程序集或模块用两个不同的证据加载了两次。An assembly or module was loaded twice with two different evidences.

此示例为 nullThis instance is null.

注解

有关更多信息,请参见 Activator.CreateInstanceFrom 方法。For more information, see the Activator.CreateInstanceFrom method.

如果使用 CreateInstanceFrom 方法来创建目标应用程序域中的实例,而不是调用的应用程序域,则会在目标应用程序域中加载该程序集。When the CreateInstanceFrom method is used to create an instance in a target application domain, other than the application domain from which the call is made, the assembly is loaded in the target application domain. 但是,如果实例在调用应用程序域中解包,则以特定方式使用已解包的实例可能会导致程序集加载到调用应用程序域中。However, if the instance is unwrapped in the calling application domain, using the unwrapped instance in certain ways can cause the assembly to be loaded into the calling application domain. 例如,在实例解包后,可能会请求其类型信息,以便以后调用其方法。For example, after the instance is unwrapped, its type information might be requested, in order to call its methods late-bound. 将程序集加载到调用应用程序域时,可能会出现异常。When the assembly is loaded into the calling application domain, exceptions can occur.

  • 如果以前将同一程序集的另一个版本加载到调用应用程序域中,或调用应用程序域的加载路径不同于目标应用程序域的加载路径,则可能会发生诸如 MissingMethodException 的异常。If another version of the same assembly was previously loaded into the calling application domain, or if the load path of the calling application domain is different from that of the target application domain, exceptions such as MissingMethodException can occur.

  • 如果调用应用程序域对实例类型进行早期绑定调用,则当尝试强制转换实例时,可能会引发 InvalidCastExceptionIf the calling application domain makes early-bound calls to the instance type, InvalidCastException can be thrown when an attempt is made to cast the instance.

安全性

FileIOPermissionAccess
用于读取包含程序集清单的文件。for the ability to read the file containing the assembly manifest. 关联的枚举: ReadAssociated enumeration: Read

WebPermission
如果程序集不是本地的,则能够访问程序集的位置。for the ability to access the location of the assembly if the assembly is not local.

另请参阅

CreateInstanceFrom(String, String, Object[])

创建在指定程序集文件中定义的指定类型的新实例。Creates a new instance of the specified type defined in the specified assembly file.

public:
 virtual System::Runtime::Remoting::ObjectHandle ^ CreateInstanceFrom(System::String ^ assemblyFile, System::String ^ typeName, cli::array <System::Object ^> ^ activationAttributes);
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes);
abstract member CreateInstanceFrom : string * string * obj[] -> System.Runtime.Remoting.ObjectHandle
override this.CreateInstanceFrom : string * string * obj[] -> System.Runtime.Remoting.ObjectHandle
Public Function CreateInstanceFrom (assemblyFile As String, typeName As String, activationAttributes As Object()) As ObjectHandle

参数

assemblyFile
String

文件的名称(包括路径),该文件包含定义所请求类型的程序集。The name, including the path, of a file that contains an assembly that defines the requested type. 该程序集是使用 LoadFrom(String) 方法加载的。The assembly is loaded using the LoadFrom(String) method.

typeName
String

FullName 属性返回的所请求类型的完全限定名称,包含命名空间而不是程序集。The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

activationAttributes
Object[]

可参与激活的一个或多个属性的数组。An array of one or more attributes that can participate in activation. 通常,为包含单个 UrlAttribute 对象的数组,该对象指定激活远程对象所需的 URL。Typically, an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

此参数与客户端激活的对象相关。客户端激活是一项传统技术,保留用于向后兼容,但不建议用于新的开发。This parameter is related to client-activated objects.Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. 应改用 Windows Communication Foundation 来开发分布式应用程序。Distributed applications should instead use Windows Communication Foundation.

返回

一个对象,它是新实例的包装,或者如果找不到 null,则为 typeNameAn object that is a wrapper for the new instance, or null if typeName is not found. 返回值需要打开包装才能访问真实对象。The return value needs to be unwrapped to access the real object.

实现

异常

assemblyFilenullassemblyFile is null.

未找到 assemblyFileassemblyFile was not found.

typeName 中未找到 assemblyFiletypeName was not found in assemblyFile.

调用方没有足够的权限调用此构造函数。The caller does not have sufficient permission to call this constructor.

未找到匹配的公共构造函数。No matching public constructor was found.

调用方不能为非继承自 MarshalByRefObject 的对象提供激活属性。The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.

在卸载的应用程序域上尝试该操作。The operation is attempted on an unloaded application domain.

assemblyFile 不是有效的程序集。assemblyFile is not a valid assembly.

- 或 --or- 当前加载的是公共语言运行时 2.0 版或更高版本,而 assemblyFile 是用更高版本编译的。Version 2.0 or later of the common language runtime is currently loaded and assemblyFile was compiled with a later version.

一个程序集或模块用两个不同的证据加载了两次。An assembly or module was loaded twice with two different evidences.

此示例为 nullThis instance is null.

注解

调用 typeName 的无参数构造函数。The parameterless constructor for typeName is invoked.

有关此方法的详细信息,请参阅 Activator.CreateInstanceFrom 方法。For more information about this method, see the Activator.CreateInstanceFrom method.

如果使用 CreateInstanceFrom 方法来创建目标应用程序域中的实例,而不是调用的应用程序域,则会在目标应用程序域中加载该程序集。When the CreateInstanceFrom method is used to create an instance in a target application domain, other than the application domain from which the call is made, the assembly is loaded in the target application domain. 但是,如果实例在调用应用程序域中解包,则以特定方式使用已解包的实例可能会导致程序集加载到调用应用程序域中。However, if the instance is unwrapped in the calling application domain, using the unwrapped instance in certain ways can cause the assembly to be loaded into the calling application domain. 例如,在实例解包后,可能会请求其类型信息,以便以后调用其方法。For example, after the instance is unwrapped, its type information might be requested, in order to call its methods late-bound. 将程序集加载到调用应用程序域时,可能会出现异常。When the assembly is loaded into the calling application domain, exceptions can occur.

  • 如果以前将同一程序集的另一个版本加载到调用应用程序域中,或调用应用程序域的加载路径不同于目标应用程序域的加载路径,则可能会发生诸如 MissingMethodException 的异常。If another version of the same assembly was previously loaded into the calling application domain, or if the load path of the calling application domain is different from that of the target application domain, exceptions such as MissingMethodException can occur.

  • 如果调用应用程序域对实例类型进行早期绑定调用,则当尝试强制转换实例时,可能会引发 InvalidCastExceptionIf the calling application domain makes early-bound calls to the instance type, InvalidCastException can be thrown when an attempt is made to cast the instance.

安全性

FileIOPermissionAccess
用于读取包含程序集清单的文件。for the ability to read the file containing the assembly manifest. 关联的枚举: ReadAssociated enumeration: Read

WebPermission
如果程序集不是本地的,则能够访问程序集的位置。for the ability to access the location of the assembly if the assembly is not local.

另请参阅

CreateInstanceFrom(String, String)

创建在指定程序集文件中定义的指定类型的新实例。Creates a new instance of the specified type defined in the specified assembly file.

public:
 virtual System::Runtime::Remoting::ObjectHandle ^ CreateInstanceFrom(System::String ^ assemblyFile, System::String ^ typeName);
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName);
abstract member CreateInstanceFrom : string * string -> System.Runtime.Remoting.ObjectHandle
override this.CreateInstanceFrom : string * string -> System.Runtime.Remoting.ObjectHandle
Public Function CreateInstanceFrom (assemblyFile As String, typeName As String) As ObjectHandle

参数

assemblyFile
String

文件的名称(包括路径),该文件包含定义所请求类型的程序集。The name, including the path, of a file that contains an assembly that defines the requested type. 该程序集是使用 LoadFrom(String) 方法加载的。The assembly is loaded using the LoadFrom(String) method.

typeName
String

FullName 属性返回的所请求类型的完全限定名称,包含命名空间而不是程序集。The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

返回

一个对象,它是新实例的包装,或者如果找不到 null,则为 typeNameAn object that is a wrapper for the new instance, or null if typeName is not found. 返回值需要打开包装才能访问真实对象。The return value needs to be unwrapped to access the real object.

实现

异常

assemblyFilenullassemblyFile is null.

- 或 --or- typeNamenulltypeName is null.

未找到 assemblyFileassemblyFile was not found.

typeName 中未找到 assemblyFiletypeName was not found in assemblyFile.

在卸载的应用程序域上尝试该操作。The operation is attempted on an unloaded application domain.

未找到无形参的公共构造函数。No parameterless public constructor was found.

调用方没有足够的权限调用此构造函数。The caller does not have sufficient permission to call this constructor.

assemblyFile 不是有效的程序集。assemblyFile is not a valid assembly.

- 或 --or- 当前加载的是公共语言运行时 2.0 版或更高版本,而 assemblyFile 是用更高版本编译的。Version 2.0 or later of the common language runtime is currently loaded and assemblyFile was compiled with a later version.

一个程序集或模块用两个不同的证据加载了两次。An assembly or module was loaded twice with two different evidences.

此示例为 nullThis instance is null.

示例

下面的示例演示如何使用 CreateInstanceFrom(String, String) 方法重载在目标应用程序域中创建对象的实例并调用其方法。The following example shows how to use the CreateInstanceFrom(String, String) method overload to create an instance of an object in a target application domain and call its methods.

该示例定义了可跨应用程序域边界进行封送的 MarshalableExample 类。The example defines the MarshalableExample class, which can be marshaled across application domain boundaries. 该示例生成当前正在执行的程序集的路径,创建目标应用程序域,并使用 CreateInstanceFrom(String, String) 方法重载将示例程序集加载到目标应用程序域中,并创建 MarshalableExample的实例。The example builds a path to the currently executing assembly, creates a target application domain, and uses the CreateInstanceFrom(String, String) method overload to load the example assembly into the target application domain and create an instance of MarshalableExample.

备注

在此示例中,路径是绝对路径,但相对路径也会起作用,因为 Assembly.LoadFrom 方法用于加载程序集。The path is absolute in this example, but a relative path would also work because the Assembly.LoadFrom method is used to load the assembly.

解包对象句柄之后,该示例演示了在目标应用程序域中使用对象的三种方法:After unwrapping the object handle, the example demonstrates three ways to use an object in a target application domain:

  • 使用反射通过后期绑定调用方法。Invoking a method with late binding, using reflection. 这需要类型信息,这会导致程序集加载到调用方的应用程序域中。This requires type information, which causes the assembly to be loaded into the application domain of the caller. (在此示例中,它已加载。)(In this example, it is already loaded.)

  • 将对象强制转换为调用方和被调用方都已知的接口。Casting the object to an interface known to both the caller and the callee. 如果接口是在调用程序集或调用方和被调用方引用的第三个程序集中定义的,则调用的程序集不会加载到调用方的应用程序域中。If the interface is defined in the calling assembly or in a third assembly referenced by both the caller and the callee, the called assembly is not loaded into the application domain of the caller.

  • 当调用方知道对象的类型时,直接使用对象。Using the object directly when its type is known to the caller. 必须将程序集加载到调用方的应用程序域中。The assembly must be loaded into the application domain of the caller.

避免将调用的程序集加载到调用方的应用程序域中的另一种方法是,调用方派生自 MarshalByRefObject 类,并定义可在目标应用程序域中运行的方法。Another way to avoid loading the called assembly into the application domain of the caller is for the caller to derive from the MarshalByRefObject class and to define a method that can be run in the target application domain. 该方法可以使用反射来检查目标程序集,因为目标程序集已加载到目标应用程序域中。That method can use reflection to examine a target assembly, because the target assembly is already loaded into the target application domain. 请参阅 DynamicDirectory 属性的示例。See the example for the DynamicDirectory property.

using namespace System;

public interface class ITest
{
    void Test(String^ greeting);
};

public ref class MarshalableExample : MarshalByRefObject, ITest
{
public:
    virtual void Test(String^ greeting)
    {
        Console::WriteLine("{0} from '{1}'!", greeting,
            AppDomain::CurrentDomain->FriendlyName);
    }
};

void main()
{
    // Construct a path to the current assembly.
    String^ assemblyPath = Environment::CurrentDirectory + "\\" +
        MarshalableExample::typeid->Assembly->GetName()->Name + ".exe";

    AppDomain^ ad = AppDomain::CreateDomain("MyDomain");
 
    System::Runtime::Remoting::ObjectHandle^ oh = 
        ad->CreateInstanceFrom(assemblyPath, "MarshalableExample");

    Object^ obj = oh->Unwrap();


    // Three ways to use the newly created object, depending on how
    // much is known about the type: Late bound, early bound through 
    // a mutually known interface, or early binding of a known type.
    //
    obj->GetType()->InvokeMember("Test", 
        System::Reflection::BindingFlags::InvokeMethod, 
        Type::DefaultBinder, obj, gcnew array<Object^> { "Hello" });

    ITest^ it = (ITest^) obj;
    it->Test("Hi");

    MarshalableExample^ ex = (MarshalableExample^) obj;
    ex->Test("Goodbye");
}

/* This example produces the following output:

Hello from 'MyDomain'!
Hi from 'MyDomain'!
Goodbye from 'MyDomain'!
 */
using System;

public interface ITest
{
    void Test(string greeting);
}

public class MarshalableExample : MarshalByRefObject, ITest
{
    static void Main()
    {
        // Construct a path to the current assembly.
        string assemblyPath = Environment.CurrentDirectory + "\\" +
            typeof(MarshalableExample).Assembly.GetName().Name + ".exe";

        AppDomain ad = AppDomain.CreateDomain("MyDomain");
 
        System.Runtime.Remoting.ObjectHandle oh = 
            ad.CreateInstanceFrom(assemblyPath, "MarshalableExample");

        object obj = oh.Unwrap();

        // Three ways to use the newly created object, depending on how
        // much is known about the type: Late bound, early bound through 
        // a mutually known interface, or early binding of a known type.
        //
        obj.GetType().InvokeMember("Test", 
            System.Reflection.BindingFlags.InvokeMethod, 
            Type.DefaultBinder, obj, new object[] { "Hello" });

        ITest it = (ITest) obj;
        it.Test("Hi");

        MarshalableExample ex = (MarshalableExample) obj;
        ex.Test("Goodbye");
    }

    public void Test(string greeting)
    {
        Console.WriteLine("{0} from '{1}'!", greeting,
            AppDomain.CurrentDomain.FriendlyName);
    }
}

/* This example produces the following output:

Hello from 'MyDomain'!
Hi from 'MyDomain'!
Goodbye from 'MyDomain'!
 */
Public Interface ITest

    Sub Test(ByVal greeting As String)
End Interface

Public Class MarshalableExample 
    Inherits MarshalByRefObject
    Implements ITest

    Shared Sub Main()
    
        ' Construct a path to the current assembly.
        Dim assemblyPath As String = Environment.CurrentDirectory & "\" &
            GetType(MarshalableExample).Assembly.GetName().Name & ".exe"

        Dim ad As AppDomain = AppDomain.CreateDomain("MyDomain")
 
        Dim oh As System.Runtime.Remoting.ObjectHandle = 
            ad.CreateInstanceFrom(assemblyPath, "MarshalableExample")

        Dim obj As Object = oh.Unwrap()


        ' Three ways to use the newly created object, depending on how
        ' much is known about the type: Late bound, early bound through 
        ' a mutually known interface, or early binding of a known type.
        '
        obj.GetType().InvokeMember("Test", 
            System.Reflection.BindingFlags.InvokeMethod, 
            Type.DefaultBinder, obj, New Object() { "Hello" })

        Dim it As ITest = CType(obj, ITest) 
        it.Test("Hi")

        Dim ex As MarshalableExample = CType(obj, MarshalableExample) 
        ex.Test("Goodbye")
    End Sub

    Public Sub Test(ByVal greeting As String) Implements ITest.Test
    
        Console.WriteLine("{0} from '{1}'!", greeting,
            AppDomain.CurrentDomain.FriendlyName)
    End Sub
End Class

' This example produces the following output:
'
'Hello from 'MyDomain'!
'Hi from 'MyDomain'!
'Goodbye from 'MyDomain'!

注解

调用 typeName 的无参数构造函数。The parameterless constructor for typeName is invoked.

有关更多信息,请参见 Activator.CreateInstanceFrom 方法。For more information, see the Activator.CreateInstanceFrom method.

如果使用 CreateInstanceFrom 方法来创建目标应用程序域中的实例,而不是调用的应用程序域,则会在目标应用程序域中加载该程序集。When the CreateInstanceFrom method is used to create an instance in a target application domain, other than the application domain from which the call is made, the assembly is loaded in the target application domain. 但是,如果实例在调用应用程序域中解包,则以特定方式使用已解包的实例可能会导致程序集加载到调用应用程序域中。However, if the instance is unwrapped in the calling application domain, using the unwrapped instance in certain ways can cause the assembly to be loaded into the calling application domain. 例如,在实例解包后,可能会请求其类型信息,以便以后调用其方法。For example, after the instance is unwrapped, its type information might be requested, in order to call its methods late-bound. 将程序集加载到调用应用程序域时,可能会出现异常。When the assembly is loaded into the calling application domain, exceptions can occur.

  • 如果以前将同一程序集的另一个版本加载到调用应用程序域中,或调用应用程序域的加载路径不同于目标应用程序域的加载路径,则可能会发生诸如 MissingMethodException 的异常。If another version of the same assembly was previously loaded into the calling application domain, or if the load path of the calling application domain is different from that of the target application domain, exceptions such as MissingMethodException can occur.

  • 如果调用应用程序域对实例类型进行早期绑定调用,则当尝试强制转换实例时,可能会引发 InvalidCastExceptionIf the calling application domain makes early-bound calls to the instance type, InvalidCastException can be thrown when an attempt is made to cast the instance.

安全性

FileIOPermissionAccess
用于读取包含程序集清单的文件。for the ability to read the file containing the assembly manifest. 关联的枚举: ReadAssociated enumeration: Read

WebPermission
如果程序集不是本地的,则能够访问程序集的位置。for the ability to access the location of the assembly if the assembly is not local.

另请参阅

适用于