Activator.CreateInstance 方法

定义

使用与指定参数匹配程度最高的构造函数创建指定类型的实例。Creates an instance of the specified type using the constructor that best matches the specified parameters.

重载

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

使用命名的程序集和最匹配所指定参数的构造函数,来创建其名称在指定的远程域中指定的类型的实例。Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.

CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

使用命名的程序集和最匹配所指定参数的构造函数,来创建其名称在指定的远程域中指定的类型的实例。Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.

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

使用指定的程序集和与指定参数匹配程度最高的构造函数来创建指定名称的类型的实例。Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.

CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo, Object[])

使用与指定参数匹配程度最高的构造函数创建指定类型的实例。Creates an instance of the specified type using the constructor that best matches the specified parameters.

CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo)

使用与指定参数匹配程度最高的构造函数创建指定类型的实例。Creates an instance of the specified type using the constructor that best matches the specified parameters.

CreateInstance(Type, Object[], Object[])

使用与指定参数匹配程度最高的构造函数创建指定类型的实例。Creates an instance of the specified type using the constructor that best matches the specified parameters.

CreateInstance(String, String, Object[])

使用已命名的程序集和无参数构造函数,创建名称已指定的类型的实例。Creates an instance of the type whose name is specified, using the named assembly and parameterless constructor.

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

使用指定的程序集和与指定参数匹配程度最高的构造函数来创建指定名称的类型的实例。Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.

CreateInstance(Type, Object[])

使用与指定参数匹配程度最高的构造函数创建指定类型的实例。Creates an instance of the specified type using the constructor that best matches the specified parameters.

CreateInstance(Type, Boolean)

使用类型的无参数构造函数创建指定类型的实例。Creates an instance of the specified type using that type's parameterless constructor.

CreateInstance(String, String)

使用已命名的程序集和无参数构造函数,创建名称已指定的类型的实例。Creates an instance of the type whose name is specified, using the named assembly and parameterless constructor.

CreateInstance(ActivationContext, String[])

创建类型的一个实例,该类型由指定的 ActivationContext 对象指定,并由指定的自定义激活数据激活。Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data.

CreateInstance(Type)

使用类型的无参数构造函数创建指定类型的实例。Creates an instance of the specified type using that type's parameterless constructor.

CreateInstance(ActivationContext)

创建类型的一个实例,该类型由指定的 ActivationContext 对象指定。Creates an instance of the type designated by the specified ActivationContext object.

CreateInstance(AppDomain, String, String)

使用命名的程序集和无参数构造函数,来创建其名称在指定的远程域中指定的类型的实例。Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and parameterless constructor.

CreateInstance<T>()

使用无参数构造函数,创建指定泛型类型参数所指定类型的实例。Creates an instance of the type designated by the specified generic type parameter, using the parameterless constructor.

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

警告

此 API 现已过时。

使用命名的程序集和最匹配所指定参数的构造函数,来创建其名称在指定的远程域中指定的类型的实例。Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(AppDomain ^ domain, System::String ^ assemblyName, 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("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 CreateInstance which does not take an Evidence parameter. See https://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
[System.Security.SecurityCritical]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (AppDomain domain, string assemblyName, 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);
static member CreateInstance : AppDomain * string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle

参数

domain
AppDomain

在其中创建名为 typeName 的类型的域。The domain where the type named typeName is created.

assemblyName
String

将在其中查找名为 typeName 的类型的程序集的名称。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,则搜索正在执行的程序集。If assemblyName is null, the executing assembly is searched.

typeName
String

首选类型的完全限定名。The fully qualified name of the preferred type.

ignoreCase
Boolean

使用 true 指定对 typeName 的搜索不区分大小写;使用 false 则指定搜索区分大小写。true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

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

使用 bindingAttrargs 来查找和标识 typeName 构造函数的对象。An object that uses bindingAttr and args to seek and identify the typeName constructor. 如果 bindernull,则使用默认联编程序。If binder is null, the default binder is used.

args
Object[]

与要调用构造函数的参数数量、顺序和类型匹配的参数数组。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 为空数组或 null,则调用不带任何参数的构造函数(无参数构造函数)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

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 对象的数组。This is typically an array that contains a single UrlAttribute object. UrlAttribute 指定激活远程对象所需的 URL。The UrlAttribute specifies the URL that is required to activate a remote object.

securityAttributes
Evidence

用于做出安全策略决策和授予代码权限的信息。Information used to make security policy decisions and grant code permissions.

返回

要访问新创建的实例则必须解包的句柄。A handle that must be unwrapped to access the newly created instance.

属性

异常

domaintypeNamenulldomain or typeName is null.

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

assemblyName 中未找到 typenametypename was not found in assemblyName.

未找到 assemblyNameassemblyName was not found.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

通过反射调用的构造函数引发异常。The constructor, which was invoked through reflection, threw an exception.

未通过 GetTypeFromProgIDGetTypeFromCLSID获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- activationAttributes 不是空数组,且正在创建的类型不是从 MarshalByRefObject 派生得来的。activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or- 最匹配 args 的构造函数具有 varargs 参数。The constructor that best matches args has varargs arguments.

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

-or- 当前已加载公共语言运行时 (CLR) 2.0 或更新版本,但 assemblyName 是使用比当前加载版本更新的 CLR 版本编译的。The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. 请注意,.NET Framework 2.0、3.0 和 3.5 都使用 CLR 2.0。Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

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

-or-

程序集名称或基本代码无效。The assembly name or code base is invalid.

注解

当主机需要在具有受限安全权限的应用程序域中执行代码时,请使用 CreateInstanceUse CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

使用 ObjectHandle.Unwrap 将返回值解包。Use ObjectHandle.Unwrap to unwrap the return value.

备注

此方法使用 SecurityAction.LinkDemand 要求直接调用方具有完全信任。This method uses SecurityAction.LinkDemand to require the immediate caller to have full trust.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于在所有类型成员上调用操作的能力。for the ability to invoke operations on all type members. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

SecurityCriticalAttribute
需要对直接调用方的完全信任。requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

使用命名的程序集和最匹配所指定参数的构造函数,来创建其名称在指定的远程域中指定的类型的实例。Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(AppDomain ^ domain, System::String ^ assemblyName, 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.SecurityCritical]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
static member CreateInstance : AppDomain * string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> System.Runtime.Remoting.ObjectHandle

参数

domain
AppDomain

在其中创建名为 typeName 的类型的域。The domain where the type named typeName is created.

assemblyName
String

将在其中查找名为 typeName 的类型的程序集的名称。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,则搜索正在执行的程序集。If assemblyName is null, the executing assembly is searched.

typeName
String

首选类型的完全限定名。The fully qualified name of the preferred type.

ignoreCase
Boolean

使用 true 指定对 typeName 的搜索不区分大小写;使用 false 则指定搜索区分大小写。true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

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

使用 bindingAttrargs 来查找和标识 typeName 构造函数的对象。An object that uses bindingAttr and args to seek and identify the typeName constructor. 如果 bindernull,则使用默认联编程序。If binder is null, the default binder is used.

args
Object[]

与要调用构造函数的参数数量、顺序和类型匹配的参数数组。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 为空数组或 null,则调用不带任何参数的构造函数(无参数构造函数)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

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。This is 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.

返回

要访问新创建的实例则必须解包的句柄。A handle that must be unwrapped to access the newly created instance.

属性

异常

domaintypeNamenulldomain or typeName is null.

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

assemblyName 中未找到 typenametypename was not found in assemblyName.

未找到 assemblyNameassemblyName was not found.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

通过反射调用的构造函数引发异常。The constructor, which was invoked through reflection, threw an exception.

未通过 GetTypeFromProgIDGetTypeFromCLSID获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- activationAttributes 不是空数组,且正在创建的类型不是从 MarshalByRefObject 派生得来的。activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or- 最匹配 args 的构造函数具有 varargs 参数。The constructor that best matches args has varargs arguments.

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

-or- 当前已加载公共语言运行时 (CLR) 2.0 或更新版本,但 assemblyName 是使用比当前加载版本更新的 CLR 版本编译的。The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. 请注意,.NET Framework 2.0、3.0 和 3.5 都使用 CLR 2.0。Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

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

-or-

程序集名称或基本代码无效。The assembly name or code base is invalid.

注解

当主机需要在具有受限安全权限的应用程序域中执行代码时,请使用 CreateInstanceUse CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

使用 ObjectHandle.Unwrap 将返回值解包。Use ObjectHandle.Unwrap to unwrap the return value.

备注

此方法使用 SecurityAction.LinkDemand 要求直接调用方具有完全信任。This method uses SecurityAction.LinkDemand to require the immediate caller to have full trust.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于在所有类型成员上调用操作的能力。for the ability to invoke operations on all type members. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

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

使用指定的程序集和与指定参数匹配程度最高的构造函数来创建指定名称的类型的实例。Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(System::String ^ assemblyName, 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 static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
static member CreateInstance : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> System.Runtime.Remoting.ObjectHandle

参数

assemblyName
String

将在其中查找名为 typeName 的类型的程序集的名称。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,则搜索正在执行的程序集。If assemblyName is null, the executing assembly is searched.

typeName
String

首选类型的完全限定名。The fully qualified name of the preferred type.

ignoreCase
Boolean

使用 true 指定对 typeName 的搜索不区分大小写;使用 false 则指定搜索区分大小写。true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

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

使用 bindingAttrargs 来查找和标识 typeName 构造函数的对象。An object that uses bindingAttr and args to seek and identify the typeName constructor. 如果 bindernull,则使用默认联编程序。If binder is null, the default binder is used.

args
Object[]

与要调用构造函数的参数数量、顺序和类型匹配的参数数组。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 为空数组或 null,则调用不带任何参数的构造函数(无参数构造函数)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

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。This is 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.

返回

要访问新创建的实例则必须解包的句柄。A handle that must be unwrapped to access the newly created instance.

异常

typeNamenulltypeName is null.

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

assemblyName 中未找到 typenametypename was not found in assemblyName.

未找到 assemblyNameassemblyName was not found.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

通过反射调用的构造函数引发异常。The constructor, which was invoked through reflection, threw an exception.

未通过 GetTypeFromProgIDGetTypeFromCLSID获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- activationAttributes 不是空数组,且正在创建的类型不是从 MarshalByRefObject 派生得来的。activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or- 最匹配 args 的构造函数具有 varargs 参数。The constructor that best matches args has varargs arguments.

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

-or- 当前已加载公共语言运行时 (CLR) 2.0 或更新版本,但 assemblyName 是使用比当前加载版本更新的 CLR 版本编译的。The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. 请注意,.NET Framework 2.0、3.0 和 3.5 都使用 CLR 2.0。Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

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

-or-

程序集名称或基本代码无效。The assembly name or code base is invalid.

注解

使用 ObjectHandle.Unwrap 将返回值解包。Use ObjectHandle.Unwrap to unwrap the return value.

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1开始,此方法可用于创建非公共类型和成员(如果已向调用方授予了 ReflectionPermissionFlag.RestrictedMemberAccess 标志 ReflectionPermission,以及包含非公共类型和成员的程序集的授予集限制为调用方的授权集或其子集。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller's grant set or to a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于访问非公共类型和成员,而不考虑其授予集。for accessing nonpublic types and members regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo, Object[])

使用与指定参数匹配程度最高的构造函数创建指定类型的实例。Creates an instance of the specified type using the constructor that best matches the specified parameters.

public:
 static System::Object ^ CreateInstance(Type ^ type, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes);
public static object CreateInstance (Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
static member CreateInstance : Type * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> obj

参数

type
Type

要创建的对象的类型。The type of object to create.

bindingAttr
BindingFlags

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

binder
Binder

使用 bindingAttrargs 来查找和标识 type 构造函数的对象。An object that uses bindingAttr and args to seek and identify the type constructor. 如果 bindernull,则使用默认联编程序。If binder is null, the default binder is used.

args
Object[]

与要调用构造函数的参数数量、顺序和类型匹配的参数数组。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 为空数组或 null,则调用不带任何参数的构造函数(无参数构造函数)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

culture
CultureInfo

区域性特定的信息,这些信息控制将 args 强制转换为 type 构造函数所声明的正式类型。Culture-specific information that governs the coercion of args to the formal types declared for the type 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。This is 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.

返回

对新创建对象的引用。A reference to the newly created object.

异常

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-or- type 是开放式泛型类型(即,ContainsGenericParameters 属性将返回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不能为 TypeBuildertype cannot be a TypeBuilder.

-or- 不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- activationAttributes 不是空数组,且正在创建的类型不是从 MarshalByRefObject 派生得来的。activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or- 包含 type 的程序集是一个用 Save 创建的动态程序集。The assembly that contains type is a dynamic assembly that was created with Save.

-or- 最匹配 args 的构造函数具有 varargs 参数。The constructor that best matches args has varargs arguments.

正在被调用的构造函数引发了一个异常。The constructor being called throws an exception.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

未通过 GetTypeFromProgIDGetTypeFromCLSID 获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

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

type 是一个 COM 对象,但用于获取类型的类标识符无效,或标识的类未注册。type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type 不是有效类型。type is not a valid type.

注解

要调用的构造函数必须在指定的联编程序和绑定特性的约束下,提供与指定参数列表最具体的匹配项。The constructor to be invoked must provide the most specific match with the specified argument list under the constraints of the specified binder and binding attributes.

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1开始,此方法可用于访问非公共类型和成员(如果已向调用方授予了 ReflectionPermissionFlag.RestrictedMemberAccess 标志的 ReflectionPermission),并且非公共类型和成员的授予集限制为调用方的授予集或 thereo 子集果.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the nonpublic types and members is restricted to the caller's grant set or to a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
用于提供证据。for supplying evidence. 关联的枚举: ControlEvidenceAssociated enumeration: ControlEvidence

ReflectionPermission
用于访问非公共类型和成员,而不考虑其授予集。for accessing nonpublic types and members regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo)

使用与指定参数匹配程度最高的构造函数创建指定类型的实例。Creates an instance of the specified type using the constructor that best matches the specified parameters.

public:
 static System::Object ^ CreateInstance(Type ^ type, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture);
public static object CreateInstance (Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture);
static member CreateInstance : Type * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo -> obj

参数

type
Type

要创建的对象的类型。The type of object to create.

bindingAttr
BindingFlags

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

binder
Binder

使用 bindingAttrargs 来查找和标识 type 构造函数的对象。An object that uses bindingAttr and args to seek and identify the type constructor. 如果 bindernull,则使用默认联编程序。If binder is null, the default binder is used.

args
Object[]

与要调用构造函数的参数数量、顺序和类型匹配的参数数组。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 为空数组或 null,则调用不带任何参数的构造函数(无参数构造函数)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

culture
CultureInfo

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

返回

对新创建对象的引用。A reference to the newly created object.

异常

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-or- type 是开放式泛型类型(即,ContainsGenericParameters 属性将返回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不能为 TypeBuildertype cannot be a TypeBuilder.

-or- 不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- 包含 type 的程序集是一个用 Save 创建的动态程序集。The assembly that contains type is a dynamic assembly that was created with Save.

-or- 最匹配 args 的构造函数具有 varargs 参数。The constructor that best matches args has varargs arguments.

正在被调用的构造函数引发了一个异常。The constructor being called throws an exception.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

未通过 GetTypeFromProgIDGetTypeFromCLSID 获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

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

type 是一个 COM 对象,但用于获取类型的类标识符无效,或标识的类未注册。type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type 不是有效类型。type is not a valid type.

注解

要调用的构造函数必须在指定的联编程序和绑定特性的约束下,提供与指定参数列表最具体的匹配项。The constructor to be invoked must provide the most specific match with the specified argument list under the constraints of the specified binder and binding attributes.

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1开始,此方法可用于访问非公共类型和成员(如果已向调用方授予了 ReflectionPermissionFlag.RestrictedMemberAccess 标志 ReflectionPermission,以及包含非公共类型和成员的程序集的授予集限制为调用方的授权集或其子集。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller's grant set or to a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于访问非公共类型和成员,而不考虑其授予集。for accessing nonpublic types and members regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(Type, Object[], Object[])

使用与指定参数匹配程度最高的构造函数创建指定类型的实例。Creates an instance of the specified type using the constructor that best matches the specified parameters.

public:
 static System::Object ^ CreateInstance(Type ^ type, cli::array <System::Object ^> ^ args, cli::array <System::Object ^> ^ activationAttributes);
public static object CreateInstance (Type type, object[] args, object[] activationAttributes);
static member CreateInstance : Type * obj[] * obj[] -> obj

参数

type
Type

要创建的对象的类型。The type of object to create.

args
Object[]

与要调用构造函数的参数数量、顺序和类型匹配的参数数组。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 为空数组或 null,则调用不带任何参数的构造函数(无参数构造函数)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

activationAttributes
Object[]

包含一个或多个可以参与激活的特性的数组。An array of one or more attributes that can participate in activation. 这通常为包含单个 UrlAttribute 对象的数组,该对象指定激活远程对象所需的 URL。This is 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.

返回

对新创建对象的引用。A reference to the newly created object.

异常

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-or- type 是开放式泛型类型(即,ContainsGenericParameters 属性将返回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不能为 TypeBuildertype cannot be a TypeBuilder.

-or- 不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- activationAttributes 不是空数组,且正在创建的类型不是从 MarshalByRefObject 派生得来的。activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or- 包含 type 的程序集是一个用 Save 创建的动态程序集。The assembly that contains type is a dynamic assembly that was created with Save.

-or- 最匹配 args 的构造函数具有 varargs 参数。The constructor that best matches args has varargs arguments.

正在被调用的构造函数引发了一个异常。The constructor being called throws an exception.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

未通过 GetTypeFromProgIDGetTypeFromCLSID 获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

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

type 是一个 COM 对象,但用于获取类型的类标识符无效,或标识的类未注册。type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type 不是有效类型。type is not a valid type.

注解

要调用的构造函数必须是可访问的,并且必须提供与指定参数列表最具体的匹配项。The constructor to be invoked must be accessible and must provide the most specific match with the specified argument list.

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1开始,此方法可用于访问非公共类型(如果已向调用方授予了 ReflectionPermissionFlag.RestrictedMemberAccess 标志 ReflectionPermission,以及包含非公共类型的程序集的授予集限制为调用方的授予集或reof.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller's grant set or to a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于访问非公共类型,而不考虑其授予集。for accessing nonpublic types regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(String, String, Object[])

使用已命名的程序集和无参数构造函数,创建名称已指定的类型的实例。Creates an instance of the type whose name is specified, using the named assembly and parameterless constructor.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(System::String ^ assemblyName, System::String ^ typeName, cli::array <System::Object ^> ^ activationAttributes);
public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes);
static member CreateInstance : string * string * obj[] -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (assemblyName As String, typeName As String, activationAttributes As Object()) As ObjectHandle

参数

assemblyName
String

将在其中查找名为 typeName 的类型的程序集的名称。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,则搜索正在执行的程序集。If assemblyName is null, the executing assembly is searched.

typeName
String

首选类型的完全限定名。The fully qualified name of the preferred type.

activationAttributes
Object[]

包含一个或多个可以参与激活的特性的数组。An array of one or more attributes that can participate in activation. 这通常为包含单个 UrlAttribute 对象的数组,该对象指定激活远程对象所需的 URL。This is 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.

返回

要访问新创建的实例则必须解包的句柄。A handle that must be unwrapped to access the newly created instance.

异常

typeNamenulltypeName is null.

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

assemblyName 中未找到 typenametypename was not found in assemblyName.

未找到 assemblyNameassemblyName was not found.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

未通过 GetTypeFromProgIDGetTypeFromCLSID 获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- activationAttributes 不是空数组,且正在创建的类型不是从 MarshalByRefObject 派生得来的。activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or- activationAttributes 不是 UrlAttributeactivationAttributes is not a UrlAttribute

数组。array.

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

-or- 当前已加载公共语言运行时 (CLR) 2.0 或更新版本,但 assemblyName 是使用比当前加载版本更新的 CLR 版本编译的。The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. 请注意,.NET Framework 2.0、3.0 和 3.5 都使用 CLR 2.0。Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

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

-or-

程序集名称或基本代码无效。The assembly name or code base is invalid.

activationAttributes 中指定的目标中尝试远程激活时出错。An error occurred when attempting remote activation in a target specified in activationAttributes.

注解

使用 ObjectHandle.Unwrap 将返回值解包。Use ObjectHandle.Unwrap to unwrap the return value.

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1开始,此方法可用于创建非公共类型,前提是已向调用方授予 ReflectionPermissionFlag.RestrictedMemberAccess 标志 ReflectionPermission,而非公共类型的授予集限制为调用方的授权集或其子集。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the nonpublic types is restricted to the caller's grant set or to a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于访问非公共类型,而不考虑其授予集。for accessing nonpublic types regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

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

警告

此 API 现已过时。

使用指定的程序集和与指定参数匹配程度最高的构造函数来创建指定名称的类型的实例。Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(System::String ^ assemblyName, 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 ^ securityInfo);
[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 CreateInstance which does not take an Evidence parameter. See https://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityInfo);
static member CreateInstance : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle

参数

assemblyName
String

将在其中查找名为 typeName 的类型的程序集的名称。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,则搜索正在执行的程序集。If assemblyName is null, the executing assembly is searched.

typeName
String

首选类型的完全限定名。The fully qualified name of the preferred type.

ignoreCase
Boolean

使用 true 指定对 typeName 的搜索不区分大小写;使用 false 则指定搜索区分大小写。true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

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

使用 bindingAttrargs 来查找和标识 typeName 构造函数的对象。An object that uses bindingAttr and args to seek and identify the typeName constructor. 如果 bindernull,则使用默认联编程序。If binder is null, the default binder is used.

args
Object[]

与要调用构造函数的参数数量、顺序和类型匹配的参数数组。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 为空数组或 null,则调用不带任何参数的构造函数(无参数构造函数)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

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。This is 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.

securityInfo
Evidence

用于做出安全策略决策和授予代码权限的信息。Information used to make security policy decisions and grant code permissions.

返回

要访问新创建的实例则必须解包的句柄。A handle that must be unwrapped to access the newly created instance.

属性

异常

typeNamenulltypeName is null.

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

assemblyName 中未找到 typenametypename was not found in assemblyName.

未找到 assemblyNameassemblyName was not found.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

通过反射调用的构造函数引发异常。The constructor, which was invoked through reflection, threw an exception.

未通过 GetTypeFromProgIDGetTypeFromCLSID获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- activationAttributes 不是空数组,且正在创建的类型不是从 MarshalByRefObject 派生得来的。activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or- 最匹配 args 的构造函数具有 varargs 参数。The constructor that best matches args has varargs arguments.

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

-or- 当前已加载公共语言运行时 (CLR) 2.0 或更新版本,但 assemblyName 是使用比当前加载版本更新的 CLR 版本编译的。The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. 请注意,.NET Framework 2.0、3.0 和 3.5 都使用 CLR 2.0。Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

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

-or-

程序集名称或基本代码无效。The assembly name or code base is invalid.

注解

使用 ObjectHandle.Unwrap 将返回值解包。Use ObjectHandle.Unwrap to unwrap the return value.

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1开始,此方法可用于创建非公共类型和成员(如果已向调用方授予了 ReflectionPermissionFlag.RestrictedMemberAccess 标志 ReflectionPermission,以及包含非公共类型和成员的程序集的授予集限制为调用方的授权集或其子集。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller's grant set or to a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于访问非公共类型和成员,而不考虑其授予集。for accessing nonpublic types and members regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(Type, Object[])

使用与指定参数匹配程度最高的构造函数创建指定类型的实例。Creates an instance of the specified type using the constructor that best matches the specified parameters.

public:
 static System::Object ^ CreateInstance(Type ^ type, cli::array <System::Object ^> ^ args);
public static object CreateInstance (Type type, object[] args);
static member CreateInstance : Type * obj[] -> obj

参数

type
Type

要创建的对象的类型。The type of object to create.

args
Object[]

与要调用构造函数的参数数量、顺序和类型匹配的参数数组。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 为空数组或 null,则调用不带任何参数的构造函数(无参数构造函数)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

返回

对新创建对象的引用。A reference to the newly created object.

异常

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-or- type 是开放式泛型类型(即,ContainsGenericParameters 属性将返回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不能为 TypeBuildertype cannot be a TypeBuilder.

-or- 不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- 包含 type 的程序集是一个用 Save 创建的动态程序集。The assembly that contains type is a dynamic assembly that was created with Save.

-or- 最匹配 args 的构造函数具有 varargs 参数。The constructor that best matches args has varargs arguments.

正在被调用的构造函数引发了一个异常。The constructor being called throws an exception.

适用于 Windows 应用商店应用的 .NET可移植类库中,改为捕获基类异常 MemberAccessExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

未通过 GetTypeFromProgIDGetTypeFromCLSID 获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

适用于 Windows 应用商店应用的 .NET可移植类库中,改为捕获基类异常 MissingMemberExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MissingMemberException, instead.

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

type 是一个 COM 对象,但用于获取类型的类标识符无效,或标识的类未注册。type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type 不是有效类型。type is not a valid type.

示例

下面的示例调用 CreateInstance(Type, Object[]) 方法来创建 String 对象。The following example calls the CreateInstance(Type, Object[]) method to create a String object. 它调用 String.String(Char[], Int32, Int32) 构造函数来实例化一个字符串,该字符串包含从第十四个位置开始的字符数组中的十个元素。It calls the String.String(Char[], Int32, Int32) constructor to instantiate a string that contains ten elements from a character array starting at the fourteenth position.

using System;

public class Example
{
   public static void Main()
   {
      // Initialize array of characters from a to z.
      Char[] chars = new Char[26]; 
      for (int ctr = 0; ctr < 26; ctr++)
         chars[ctr] = (char) (ctr + 0x0061);

      Object obj = Activator.CreateInstance(typeof(String),
                                            new Object[] { chars, 13, 10 } );
      Console.WriteLine(obj);                                          
   }
}
// The example displays the following output:
//       nopqrstuvw
Module Example
   Public Sub Main()
      ' Initialize array of characters from a to z.
      Dim chars(25) As Char 
      For ctr As Short = 0 To 25
         chars(ctr) = ChrW(ctr + &h0061)
      Next 
      Dim obj As Object = Activator.CreateInstance(GetType(String),
                                                   { chars, 13, 10 })
      Console.WriteLine(obj)                                          
   End Sub
End Module
' The example displays the following output:
'       nopqrstuvw

下面的示例创建一个交错数组,其元素是要传递到 String 构造函数的参数。The following example creates a jagged array whose elements are arguments to be passed to a String constructor. 然后,该示例将每个数组传递到 CreateInstance(Type, Object[]) 方法,以调用适当的字符串构造函数。The example then passes each array to the CreateInstance(Type, Object[]) method to invoke the appropriate string constructor.

using System;

public class Example
{
   public static void Main()
   {
      char[] characters = { 'a', 'b', 'c', 'd', 'e', 'f' };
      object[][] arguments = new object[3][] { new object[] { characters },
                                               new object[] { characters, 1, 4 },
                                               new object[] { characters[1], 20 } };

      for (int ctr = 0; ctr <= arguments.GetUpperBound(0); ctr++) {
         object[] args = arguments[ctr];
         object result = Activator.CreateInstance(typeof(String), args);
         Console.WriteLine("{0}: {1}", result.GetType().Name, result);
      }
   }
}
// The example displays the following output:
//    String: abcdef
//    String: bcde
//    String: bbbbbbbbbbbbbbbbbbbb
Module Example
   Public Sub Main()
      Dim characters() As Char = { "a"c, "b"c, "c"c, "d"c, "e"c, "f"c }
      Dim arguments()() As Object = new Object(2)() { New Object() { characters },
                                                      New Object() { characters, 1, 4 },
                                                      New Object() { characters(1), 20 } }

      For ctr As Integer = 0 To arguments.GetUpperBound(0)
         Dim args() As Object = arguments(ctr)
         Dim result As Object = Activator.CreateInstance(GetType(String), args)
         Console.WriteLine("{0}: {1}", result.GetType().Name, result)
      Next
   End Sub
End Module
' The example displays the following output:
'       String: abcdef
'       String: bcde
'       String: bbbbbbbbbbbbbbbbbbbb

注解

要调用的构造函数必须是可访问的,并且必须提供与指定参数列表最具体的匹配项。The constructor to be invoked must be accessible and must provide the most specific match with the specified argument list.

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1开始,此方法可用于访问非公共类型(如果已向调用方授予了 ReflectionPermissionFlag.RestrictedMemberAccess 标志 ReflectionPermission,以及包含非公共类型的程序集的授予集限制为调用方的授予集或reof.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller's grant set or to a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于访问非公共类型,而不考虑其授予集。for accessing nonpublic types regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(Type, Boolean)

使用类型的无参数构造函数创建指定类型的实例。Creates an instance of the specified type using that type's parameterless constructor.

public:
 static System::Object ^ CreateInstance(Type ^ type, bool nonPublic);
public static object CreateInstance (Type type, bool nonPublic);
static member CreateInstance : Type * bool -> obj

参数

type
Type

要创建的对象的类型。The type of object to create.

nonPublic
Boolean

如果公共或非公共无参数构造函数可以匹配,则为 true;如果只有公共无参数构造函数可以匹配,则为 falsetrue if a public or nonpublic parameterless constructor can match; false if only a public parameterless constructor can match.

返回

对新创建对象的引用。A reference to the newly created object.

异常

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-or- type 是开放式泛型类型(即,ContainsGenericParameters 属性将返回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不能为 TypeBuildertype cannot be a TypeBuilder.

-or- 不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- 包含 type 的程序集是一个用 Save 创建的动态程序集。The assembly that contains type is a dynamic assembly that was created with Save.

正在被调用的构造函数引发了一个异常。The constructor being called throws an exception.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

未通过 GetTypeFromProgIDGetTypeFromCLSID 获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

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

type 是一个 COM 对象,但用于获取类型的类标识符无效,或标识的类未注册。type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type 不是有效类型。type is not a valid type.

注解

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1开始,此方法可用于访问非公共类型和成员(如果已向调用方授予了 ReflectionPermissionFlag.RestrictedMemberAccess 标志 ReflectionPermission,以及包含非公共类型和成员的程序集的授予集限制为调用方的授权集或其子集。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller's grant set or to a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于访问非公共类型和成员,而不考虑其授予集。for accessing nonpublic types and members regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(String, String)

使用已命名的程序集和无参数构造函数,创建名称已指定的类型的实例。Creates an instance of the type whose name is specified, using the named assembly and parameterless constructor.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(System::String ^ assemblyName, System::String ^ typeName);
public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName);
static member CreateInstance : string * string -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (assemblyName As String, typeName As String) As ObjectHandle

参数

assemblyName
String

将在其中查找名为 typeName 的类型的程序集的名称。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,则搜索正在执行的程序集。If assemblyName is null, the executing assembly is searched.

typeName
String

首选类型的完全限定名。The fully qualified name of the preferred type.

返回

要访问新创建的实例则必须解包的句柄。A handle that must be unwrapped to access the newly created instance.

异常

typeNamenulltypeName is null.

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

assemblyName 中未找到 typenametypename was not found in assemblyName.

未找到 assemblyNameassemblyName was not found.

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

你无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。You cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

通过反射调用的构造函数引发异常。The constructor, which was invoked through reflection, threw an exception.

未通过 GetTypeFromProgIDGetTypeFromCLSID获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

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

-or- 当前已加载公共语言运行时 (CLR) 2.0 或更新版本,但 assemblyName 是使用比当前加载版本更新的 CLR 版本编译的。The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. 请注意,.NET Framework 2.0、3.0 和 3.5 都使用 CLR 2.0。Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

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

-or-

程序集名称或基本代码无效。The assembly name or code base is invalid.

示例

下面的示例在名为 PersonInfo的程序集中定义名为 Person 的类。The following example defines a class named Person in an assembly named PersonInfo. 请注意,Person 类有两个构造函数,其中一个是无参数的构造函数。Note that the Person class has two constructors, one of which is parameterless.

using System;

public class Person
{
   private string _name;
   
   public Person()
   { }
   
   public Person(string name)
   {
      this._name = name;
   }
   
   public string Name
   { get { return this._name; }
     set { this._name = value; } }
   
   public override string ToString()
   {
      return this._name;
   }
}
Public Class Person
   Private _name As String
   
   Public Sub New()
   End Sub
   
   Public Sub New(name As String)
      Me._name = name
   End Sub
   
   Public Property Name As String
      Get
         Return Me._name
      End Get
      Set
         Me._name = value
      End Set
   End Property
   
   Public Overrides Function ToString() As String
      Return Me._name
   End Function
End Class

下面的示例调用 CreateInstance(String, String) 方法来实例化 Person 类。The following example calls the CreateInstance(String, String) method to instantiate the Person class. 它需要将对 PersonInfo 的引用添加到该项目中。It requires a reference to PersonInfo.dll to be added to the project. 由于 CreateInstance(String, String) 方法调用 Person 类无参数构造函数,因此该示例将值赋给其 Name 属性。Because the CreateInstance(String, String) method calls the Person class parameterless constructor, the example assigns a value to its Name property.

using System;
using System.Runtime.Remoting;

public class Example
{
   public static void Main()
   {
      ObjectHandle handle = Activator.CreateInstance("PersonInfo", "Person");
      Person p = (Person) handle.Unwrap();
      p.Name = "Samuel";
      Console.WriteLine(p);
   }
}
// The example displays the following output:
//        Samuel
Imports System.Runtime.Remoting

Module Example
   Public Sub Main()
      Dim handle As ObjectHandle = Activator.CreateInstance("PersonInfo", "Person")
      Dim p As Person = CType(handle.Unwrap(), Person)
      p.Name = "Samuel"
      Console.WriteLine(p)
   End Sub
End Module
' The example displays the following output:
'       Samuel

但是,通常调用 CreateInstance 来实例化跨计算机边界的类型或在设计时不知道的类型。However, CreateInstance is frequently called to instantiate a type that crosses machine boundaries or that is not known at design time. 在这种情况下,不能在项目中包括对程序集的引用,并且无法对类型的成员进行早期绑定调用。In this case, you cannot include a reference to the assembly in the project and cannot make early-bound calls to the type's members. 若要解决此限制,以下示例使用 CreateInstance 方法和反射来向 Person 对象的 Name 属性赋值并显示其值。To work around this limitation, the following example uses the CreateInstance method along with reflection to assign a value to the Person object's Name property and to display its value.

using System;
using System.Reflection;
using System.Runtime.Remoting;

public class Example
{
   public static void Main()
   {
      ObjectHandle handle = Activator.CreateInstance("PersonInfo", "Person");
      Object p = handle.Unwrap();
      Type t = p.GetType();
      PropertyInfo prop = t.GetProperty("Name");
      if (prop != null)
         prop.SetValue(p, "Samuel");

      MethodInfo method = t.GetMethod("ToString");
      Object retVal = method.Invoke(p, null); 
      if (retVal != null)
         Console.WriteLine(retVal);
   }
}
// The example displays the following output:
//        Samuel
Imports System.Reflection
Imports System.Runtime.Remoting

Module Example
   Public Sub Main()
      Dim handle As ObjectHandle = Activator.CreateInstance("PersonInfo", "Person")
      Dim p As Object = handle.Unwrap()
      Dim t As Type = p.GetType()
      Dim prop As PropertyInfo = t.GetProperty("Name")
      if Not prop Is Nothing Then
         prop.SetValue(p, "Samuel")
      End If   
      Dim method As MethodInfo = t.GetMethod("ToString")
      Dim retVal As Object = method.Invoke(p, Nothing) 
      If Not retVal Is Nothing Then
         Console.WriteLine(retVal)
      End If
   End Sub
End Module
' The example displays the following output:
'       Samuel

注解

使用 ObjectHandle.Unwrap 将返回值解包。Use ObjectHandle.Unwrap to unwrap the return value.

assemblyName 可以是以下之一:assemblyName can be either of the following:

  • 程序集的简单名称,没有路径或文件扩展名。The simple name of an assembly, without its path or file extension. 例如,您可以为 .\bin\TypeExtensions.dll. 的路径和名称指定的程序集指定 TypeExtensionsFor example, you would specify TypeExtensions for an assembly whose path and name are .\bin\TypeExtensions.dll.

  • 签名程序集的全名,由其简单名称、版本、区域性和公钥标记组成;例如,"TypeExtensions,Version = 1.0.0.0,Culture = 中立,PublicKeyToken = 181869f2f7435b51"。The full name of a signed assembly, which consists of its simple name, version, culture, and public key token; for example, "TypeExtensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=181869f2f7435b51".

有关公共语言运行时如何识别和加载程序集的详细信息,请参阅运行时如何定位程序集For more information on how the common language runtime identifies and loads assemblies, see How the Runtime Locates Assemblies. 有关使用应用程序配置文件来定义程序集位置的信息,请参阅指定程序集的位置For information on using the application configuration file to define assembly locations, see Specifying an Assembly's Location. 如果找到 assemblyName,它将加载到默认上下文中。If assemblyName is found, it is loaded in the default context.

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1开始,此方法可用于创建非公共类型,前提是已向调用方授予了 ReflectionPermissionFlag.RestrictedMemberAccess 标志 ReflectionPermission 并且包含非公共类型的程序集的授予集限制为调用方的授予集或reof.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller's grant set or to a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于访问非公共类型,而不考虑其授予集。for accessing nonpublic types regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(ActivationContext, String[])

创建类型的一个实例,该类型由指定的 ActivationContext 对象指定,并由指定的自定义激活数据激活。Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(ActivationContext ^ activationContext, cli::array <System::String ^> ^ activationCustomData);
public static System.Runtime.Remoting.ObjectHandle CreateInstance (ActivationContext activationContext, string[] activationCustomData);
static member CreateInstance : ActivationContext * string[] -> System.Runtime.Remoting.ObjectHandle

参数

activationContext
ActivationContext

一个激活上下文对象,用于指定要创建的对象。An activation context object that specifies the object to create.

activationCustomData
String[]

一个包含自定义激活数据的 Unicode 字符串数组。An array of Unicode strings that contain custom activation data.

返回

要访问新创建的对象则必须解包的句柄。A handle that must be unwrapped to access the newly created object.

注解

使用 ObjectHandle.Unwrap 方法将返回值解包。Use the ObjectHandle.Unwrap method to unwrap the return value.

激活上下文在基于清单的激活过程中用于设置域策略并提供基于应用程序的安全模型。The activation context is used during manifest-based activation to set up the domain policy and to provide an application-based security model. ActivationContext 类包含一个 ApplicationIdentity 对象,该对象提供对应用程序清单的访问。The ActivationContext class contains an ApplicationIdentity object that provides access to the application manifest. 有关更多信息,请参见 ApplicationSecurityManager 类。For more information, see the ApplicationSecurityManager class.

另请参阅

CreateInstance(Type)

使用类型的无参数构造函数创建指定类型的实例。Creates an instance of the specified type using that type's parameterless constructor.

public:
 static System::Object ^ CreateInstance(Type ^ type);
public static object CreateInstance (Type type);
static member CreateInstance : Type -> obj

参数

type
Type

要创建的对象的类型。The type of object to create.

返回

对新创建对象的引用。A reference to the newly created object.

异常

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-or- type 是开放式泛型类型(即,ContainsGenericParameters 属性将返回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不能为 TypeBuildertype cannot be a TypeBuilder.

-or- 不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or- 包含 type 的程序集是一个用 Save 创建的动态程序集。The assembly that contains type is a dynamic assembly that was created with Save.

正在被调用的构造函数引发了一个异常。The constructor being called throws an exception.

适用于 Windows 应用商店应用的 .NET可移植类库中,改为捕获基类异常 MemberAccessExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.

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

无法创建抽象类的实例,或者此成员是使用晚期绑定机制调用的。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

未通过 GetTypeFromProgIDGetTypeFromCLSID 获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

适用于 Windows 应用商店应用的 .NET可移植类库中,改为捕获基类异常 MissingMemberExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MissingMemberException, instead.

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

type 是一个 COM 对象,但用于获取类型的类标识符无效,或标识的类未注册。type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type 不是有效类型。type is not a valid type.

示例

下面的代码示例演示如何调用 CreateInstance(Type) 方法。The following code example demonstrates how to call the CreateInstance(Type) method. 将创建几个不同类型的实例,并显示其默认值。Instances of several different types are created and their default values are displayed.

using namespace System;

ref class DynamicInstanceList
{
private:
    static String^ instanceSpec = "System.EventArgs;System.Random;" +
        "System.Exception;System.Object;System.Version";

public:
    static void Main()
    {
        array<String^>^ instances = instanceSpec->Split(';');
        Array^ instlist = Array::CreateInstance(Object::typeid, instances->Length);
        Object^ item;

        for (int i = 0; i < instances->Length; i++)
        {
            // create the object from the specification string
            Console::WriteLine("Creating instance of: {0}", instances[i]);
            item = Activator::CreateInstance(Type::GetType(instances[i]));
            instlist->SetValue(item, i);
        }
        Console::WriteLine("\nObjects and their default values:\n");
        for each (Object^ o in instlist)
        {
            Console::WriteLine("Type:     {0}\nValue:    {1}\nHashCode: {2}\n",
                o->GetType()->FullName, o->ToString(), o->GetHashCode());
        }
    }
};

int main()
{
    DynamicInstanceList::Main();
}

// This program will display output similar to the following:
//
// Creating instance of: System.EventArgs
// Creating instance of: System.Random
// Creating instance of: System.Exception
// Creating instance of: System.Object
// Creating instance of: System.Version
//
// Objects and their default values:
//
// Type:     System.EventArgs
// Value:    System.EventArgs
// HashCode: 46104728
//
// Type:     System.Random
// Value:    System.Random
// HashCode: 12289376
//
// Type:     System.Exception
// Value:    System.Exception: Exception of type 'System.Exception' was thrown.
// HashCode: 55530882
//
// Type:     System.Object
// Value:    System.Object
// HashCode: 30015890
//
// Type:     System.Version
// Value:    0.0
// HashCode: 1048575
using System;

class DynamicInstanceList
{
    private static string instanceSpec = "System.EventArgs;System.Random;" +
        "System.Exception;System.Object;System.Version";

    public static void Main()
    {
        string[] instances = instanceSpec.Split(';');
        Array instlist = Array.CreateInstance(typeof(object), instances.Length);
        object item;
        for (int i = 0; i < instances.Length; i++)
        {
            // create the object from the specification string
            Console.WriteLine("Creating instance of: {0}", instances[i]);
            item = Activator.CreateInstance(Type.GetType(instances[i]));
            instlist.SetValue(item, i);
        }
        Console.WriteLine("\nObjects and their default values:\n");
        foreach (object o in instlist)
        {
            Console.WriteLine("Type:     {0}\nValue:    {1}\nHashCode: {2}\n",
                o.GetType().FullName, o.ToString(), o.GetHashCode());
        }
    }
}

// This program will display output similar to the following:
//
// Creating instance of: System.EventArgs
// Creating instance of: System.Random
// Creating instance of: System.Exception
// Creating instance of: System.Object
// Creating instance of: System.Version
//
// Objects and their default values:
//
// Type:     System.EventArgs
// Value:    System.EventArgs
// HashCode: 46104728
//
// Type:     System.Random
// Value:    System.Random
// HashCode: 12289376
//
// Type:     System.Exception
// Value:    System.Exception: Exception of type 'System.Exception' was thrown.
// HashCode: 55530882
//
// Type:     System.Object
// Value:    System.Object
// HashCode: 30015890
//
// Type:     System.Version
// Value:    0.0
// HashCode: 1048575
Class DynamicInstanceList
    Private Shared instanceSpec As String = "System.EventArgs;System.Random;" + _
        "System.Exception;System.Object;System.Version"

    Public Shared Sub Main()
        Dim instances() As String = instanceSpec.Split(";")
        Dim instlist As Array = Array.CreateInstance(GetType(Object), instances.Length)
        Dim item As Object

        For i As Integer = 0 To instances.Length -1
            ' create the object from the specification string
            Console.WriteLine("Creating instance of: {0}", instances(i))
            item = Activator.CreateInstance(Type.GetType(instances(i)))
            instlist.SetValue(item, i)
        Next i
        Console.WriteLine(vbNewLine + "Objects and their default values:" + vbNewLine)
        For Each o As Object In instlist
            Console.WriteLine("Type:     {0}" + vbNewLine + "Value:    {1}" + _
                vbNewLine + "HashCode: {2}" + vbNewLine, _
                o.GetType().FullName, o.ToString(), o.GetHashCode())
        Next o
    End Sub
End Class

' This program will display output similar to the following:
'
' Creating instance of: System.EventArgs
' Creating instance of: System.Random
' Creating instance of: System.Exception
' Creating instance of: System.Object
' Creating instance of: System.Version
'
' Objects and their default values:
'
' Type:     System.EventArgs
' Value:    System.EventArgs
' HashCode: 46104728
'
' Type:     System.Random
' Value:    System.Random
' HashCode: 12289376
'
' Type:     System.Exception
' Value:    System.Exception: Exception of type 'System.Exception' was thrown.
' HashCode: 55530882
'
' Type:     System.Object
' Value:    System.Object
' HashCode: 30015890
'
' Type:     System.Version
' Value:    0.0
' HashCode: 1048575

注解

要调用的构造函数必须是可访问的。The constructor to be invoked must be accessible.

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1开始,此方法可用于访问非公共类型(如果已向调用方授予了 ReflectionPermissionFlag.RestrictedMemberAccess 标志 ReflectionPermission,以及包含非公共类型的程序集的授予集限制为调用方的授予集或reof.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller's grant set or to a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于访问非公共类型,而不考虑其授予集。for accessing nonpublic types regardless of their grant sets. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(ActivationContext)

创建类型的一个实例,该类型由指定的 ActivationContext 对象指定。Creates an instance of the type designated by the specified ActivationContext object.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(ActivationContext ^ activationContext);
public static System.Runtime.Remoting.ObjectHandle CreateInstance (ActivationContext activationContext);
static member CreateInstance : ActivationContext -> System.Runtime.Remoting.ObjectHandle

参数

activationContext
ActivationContext

一个激活上下文对象,用于指定要创建的对象。An activation context object that specifies the object to create.

返回

要访问新创建的对象则必须解包的句柄。A handle that must be unwrapped to access the newly created object.

注解

使用 ObjectHandle.Unwrap 方法将返回值解包。Use the ObjectHandle.Unwrap method to unwrap the return value.

激活上下文在基于清单的激活过程中用于设置域策略并提供基于应用程序的安全模型。The activation context is used during manifest-based activation to set up the domain policy and to provide an application-based security model. ActivationContext 类包含一个 ApplicationIdentity 对象,该对象提供对应用程序清单的访问。The ActivationContext class contains an ApplicationIdentity object that provides access to the application manifest. 有关更多信息,请参见 ApplicationSecurityManager 类。For more information, see the ApplicationSecurityManager class.

另请参阅

CreateInstance(AppDomain, String, String)

使用命名的程序集和无参数构造函数,来创建其名称在指定的远程域中指定的类型的实例。Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and parameterless constructor.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(AppDomain ^ domain, System::String ^ assemblyName, System::String ^ typeName);
[System.Security.SecurityCritical]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName);
static member CreateInstance : AppDomain * string * string -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (domain As AppDomain, assemblyName As String, typeName As String) As ObjectHandle

参数

domain
AppDomain

在其中创建名为 typeName 的类型的远程域。The remote domain where the type named typeName is created.

assemblyName
String

将在其中查找名为 typeName 的类型的程序集的名称。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,则搜索正在执行的程序集。If assemblyName is null, the executing assembly is searched.

typeName
String

首选类型的完全限定名。The fully qualified name of the preferred type.

返回

要访问新创建的实例则必须解包的句柄。A handle that must be unwrapped to access the newly created instance.

属性

异常

typeNamedomainnulltypeName or domain is null.

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

assemblyName 中未找到 typenametypename was not found in assemblyName.

未找到 assemblyNameassemblyName was not found.

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

无法创建抽象类型的实例。Cannot create an instance of an abstract type.

-or-

使用晚期绑定机制调用了此成员。This member was invoked with a late-binding mechanism.

通过反射调用的构造函数引发异常。The constructor, which was invoked through reflection, threw an exception.

未通过 GetTypeFromProgIDGetTypeFromCLSID获取 COM 类型。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

不支持创建 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 类型,或者这些类型的数组。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

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

-or- 当前已加载公共语言运行时 (CLR) 2.0 或更新版本,但 assemblyName 是使用比当前加载版本更新的 CLR 版本编译的。The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. 请注意,.NET Framework 2.0、3.0 和 3.5 都使用 CLR 2.0。Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

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

-or-

程序集名称或基本代码无效。The assembly name or code base is invalid.

注解

当主机需要在具有受限安全权限的应用程序域中执行代码时,请使用 CreateInstanceUse CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

使用 ObjectHandle.Unwrap 将返回值解包。Use ObjectHandle.Unwrap to unwrap the return value.

备注

此方法使用 SecurityAction.LinkDemand 要求直接调用方具有完全信任。This method uses SecurityAction.LinkDemand to require the immediate caller to have full trust.

安全性

SecurityPermission
用于在创建委托的实例时调用非托管代码的能力。for the ability to call unmanaged code when creating an instance of a delegate. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用于在所有类型成员上调用操作的能力。for the ability to invoke operations on all type members. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

SecurityCriticalAttribute
需要对直接调用方的完全信任。requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

CreateInstance<T>()

使用无参数构造函数,创建指定泛型类型参数所指定类型的实例。Creates an instance of the type designated by the specified generic type parameter, using the parameterless constructor.

public:
generic <typename T>
 static T CreateInstance();
public static T CreateInstance<T> ();
static member CreateInstance : unit -> 'T
Public Shared Function CreateInstance(Of T) () As T

类型参数

T

要创建的类型。The type to create.

返回

T

对新创建对象的引用。A reference to the newly created object.

异常

适用于 Windows 应用商店应用的 .NET可移植类库中,改为捕获基类异常 MissingMemberExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MissingMemberException, instead.

无法创建抽象类的实例;或者,为 T 指定的类型没有无参数的构造函数。Cannot create an instance of an abstract class, or the type that is specified for T does not have a parameterless constructor.

注解

编译器使用 CreateInstance<T>() 泛型方法来实现由类型参数指定的类型的实例化。The CreateInstance<T>() generic method is used by compilers to implement the instantiation of types specified by type parameters. 例如,在下面的泛型方法中,new T() 的实现(gcnew T() 中C++)使用 CreateInstance<T>() 泛型方法。For example, in the following generic method, the implementation of new T() (gcnew T() in C++) uses the CreateInstance<T>() generic method.

public:
    generic <typename T> where T:gcnew()
    static T Bar()
    {
        return gcnew T();
    }
public static T Factory<T>() where T : new()
{
    return new T();
}
Public Shared Function Factory(Of T As New)() As T
    Return New T()
End Function

通常,应用程序代码中不使用 CreateInstance<T>() 泛型方法,因为该类型在编译时必须是已知的。In general, there is no use for the CreateInstance<T>() generic method in application code, because the type must be known at compile time. 如果该类型在编译时是已知的,则可以使用普通的实例化语法( C#new 中的运算符,New Visual Basic C++,gcnew 中)。If the type is known at compile time, normal instantiation syntax can be used (new operator in C#, New in Visual Basic, gcnew in C++). 如果类型在编译时未知,则可以调用 CreateInstance的非泛型重载。If the type is not known at compile time, you can call a non-generic overload of CreateInstance.

不存在采用参数列表的 CreateInstance<T>() 泛型方法的重载,因为 CreateInstance 的非泛型重载已经提供后期绑定构造函数解析。There are no overloads of the CreateInstance<T>() generic method that take argument lists, because the non-generic overloads of CreateInstance already provide late-bound constructor resolution.

适用于