Activator.CreateInstance Activator.CreateInstance Activator.CreateInstance Activator.CreateInstance Method

定义

使用与指定参数匹配程度最高的构造函数创建指定类型的实例。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) CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) 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[]) CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) 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[]) CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) 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[]) CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo, Object[]) 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) CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo) 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[]) CreateInstance(Type, Object[], Object[]) CreateInstance(Type, Object[], Object[])

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

CreateInstance(String, String, Object[]) CreateInstance(String, String, Object[]) CreateInstance(String, String, Object[]) CreateInstance(String, String, Object[])

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

CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) 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[]) CreateInstance(Type, Object[]) CreateInstance(Type, Object[])

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

CreateInstance(Type, Boolean) CreateInstance(Type, Boolean) CreateInstance(Type, Boolean)

使用指定类型的默认构造函数来创建该类型的实例。Creates an instance of the specified type using that type's default constructor.

CreateInstance(String, String) CreateInstance(String, String) CreateInstance(String, String) CreateInstance(String, String)

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

CreateInstance(ActivationContext, String[]) CreateInstance(ActivationContext, String[]) 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) CreateInstance(Type) CreateInstance(Type)

使用指定类型的默认构造函数来创建该类型的实例。Creates an instance of the specified type using that type's default constructor.

CreateInstance(ActivationContext) CreateInstance(ActivationContext) CreateInstance(ActivationContext)

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

CreateInstance(AppDomain, String, String) CreateInstance(AppDomain, String, String) CreateInstance(AppDomain, String, String) CreateInstance(AppDomain, String, String)

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

CreateInstance<T>() CreateInstance<T>() CreateInstance<T>() 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) CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) 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 http://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 AppDomain AppDomain AppDomain

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

assemblyName
String String String 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 String String String

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

ignoreCase
Boolean Boolean Boolean 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 BindingFlags BindingFlags 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 Binder 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 default constructor) is invoked.

culture
CultureInfo CultureInfo CultureInfo 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 Evidence Evidence 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.

不支持创建 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.

注解

使用CreateInstance主机需要具有受限的安全权限的应用程序域中执行代码。Use 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[]) CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) 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 AppDomain AppDomain AppDomain

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

assemblyName
String String String 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 String String String

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

ignoreCase
Boolean Boolean Boolean 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 BindingFlags BindingFlags 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 Binder 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 default constructor) is invoked.

culture
CultureInfo CultureInfo CultureInfo 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.

不支持创建 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.

注解

使用CreateInstance主机需要具有受限的安全权限的应用程序域中执行代码。Use 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[]) CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) 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 String String 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 String String String

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

ignoreCase
Boolean Boolean Boolean 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 BindingFlags BindingFlags 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 Binder 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 default constructor) is invoked.

culture
CultureInfo CultureInfo CultureInfo 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.

异常

未找到匹配的构造函数。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.

不支持创建 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,此方法可用于创建非公共类型和成员调用方是否已被授予ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志和包含的非公共类型和成员的程序集的授予集是受限制调用方的授予集或其子集。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[]) CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo, Object[]) 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 Type Type Type

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

bindingAttr
BindingFlags BindingFlags BindingFlags 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 Binder 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 default constructor) is invoked.

culture
CultureInfo CultureInfo CultureInfo 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.

异常

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.

未找到匹配的构造函数。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,此方法可用于访问非公共类型和成员调用方是否已被授予ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志和非公共类型和成员的授予集如果被限制到调用方的授予集或其子集。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) CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo) 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 Type Type Type

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

bindingAttr
BindingFlags BindingFlags BindingFlags 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 Binder 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 default constructor) is invoked.

culture
CultureInfo CultureInfo CultureInfo 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.

异常

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.

未找到匹配的构造函数。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,此方法可用于访问非公共类型和成员调用方是否已被授予ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志和包含的非公共类型和成员的程序集的授予集是受限制调用方的授予集或其子集。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[]) CreateInstance(Type, Object[], Object[]) 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 Type 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 default 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.

异常

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.

未找到匹配的公共构造函数。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,可以使用此方法访问非公共类型,如果授予调用方ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志,如果包含非公共类型的程序集的授予集被限制到调用方的授权设置或其子集。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[]) CreateInstance(String, String, Object[]) CreateInstance(String, String, Object[]) CreateInstance(String, String, Object[])

使用命名的程序集和默认构造函数,创建名称已指定的类型的实例。Creates an instance of the type whose name is specified, using the named assembly and default 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 String String 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 String String 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.

异常

未找到匹配的公共构造函数。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.

不支持创建 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,此方法可用于创建非公共类型,如果授予调用方ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志和非公共类型的授予集是否限制调用方的授予集或其子集。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) CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) 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 http://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 String String 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 String String String

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

ignoreCase
Boolean Boolean Boolean 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 BindingFlags BindingFlags 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 Binder 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 default constructor) is invoked.

culture
CultureInfo CultureInfo CultureInfo 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 Evidence Evidence Evidence

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

返回

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

异常

未找到匹配的构造函数。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.

不支持创建 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,此方法可用于创建非公共类型和成员调用方是否已被授予ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志和包含的非公共类型和成员的程序集的授予集是受限制调用方的授予集或其子集。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[]) CreateInstance(Type, Object[]) 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, params object[] args);
static member CreateInstance : Type * obj[] -> obj

参数

type
Type Type 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 default constructor) is invoked.

返回

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

异常

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.

适用于 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)构造函数实例化一个字符串,包含从字符数组的第 14 个位置开始的 10 个元素。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,可以使用此方法访问非公共类型,如果授予调用方ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志,如果包含非公共类型的程序集的授予集被限制到调用方的授权设置或其子集。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) CreateInstance(Type, Boolean) CreateInstance(Type, Boolean)

使用指定类型的默认构造函数来创建该类型的实例。Creates an instance of the specified type using that type's default 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 Type Type Type

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

nonPublic
Boolean Boolean Boolean Boolean

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

返回

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

异常

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.

未找到匹配的公共构造函数。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,此方法可用于访问非公共类型和成员调用方是否已被授予ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志和包含的非公共类型和成员的程序集的授予集是受限制调用方的授予集或其子集。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) CreateInstance(String, String) CreateInstance(String, String) CreateInstance(String, String)

使用命名的程序集和默认构造函数,创建名称已指定的类型的实例。Creates an instance of the type whose name is specified, using the named assembly and default 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 String String 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 String String String

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

返回

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

异常

未找到匹配的公共构造函数。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.

不支持创建 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.

示例

下面的示例定义一个名为Person程序集中名为PersonInfoThe 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.dll 要添加到项目的引用。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 default 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. 例如,将指定TypeExtensions其路径和名称是.\bin\TypeExtensions.dll 程序集。For example, you would specify TypeExtensions for an assembly whose path and name are .\bin\TypeExtensions.dll.

  • 签名的程序集,其中包括其简单名称、 版本、 区域性和公钥标记; 完整名称例如,"TypeExtensions,版本 = 1.0.0.0,区域性 = 中性,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,此方法可用于创建非公共类型,如果授予调用方ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志,如果包含非公共类型的程序集的授予集被限制到调用方的授权设置或其子集。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[]) CreateInstance(ActivationContext, String[]) 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 ActivationContext 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) CreateInstance(Type) CreateInstance(Type)

使用指定类型的默认构造函数来创建该类型的实例。Creates an instance of the specified type using that type's default constructor.

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

参数

type
Type Type Type Type

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

返回

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

异常

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.

适用于 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
Imports System

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,可以使用此方法访问非公共类型,如果授予调用方ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志,如果包含非公共类型的程序集的授予集被限制到调用方的授权设置或其子集。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) CreateInstance(ActivationContext) 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 ActivationContext 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) CreateInstance(AppDomain, String, String) CreateInstance(AppDomain, String, String) CreateInstance(AppDomain, String, String)

使用命名的程序集和默认构造函数,来创建其名称在指定的远程域中指定的类型的实例。Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and default 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 AppDomain AppDomain AppDomain

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

assemblyName
String String String 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 String String 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.

不支持创建 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.

注解

使用CreateInstance主机需要具有受限的安全权限的应用程序域中执行代码。Use 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>() CreateInstance<T>() CreateInstance<T>() 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 T T 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 指定的类型没有无参数构造函数。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. 如果在编译时已知类型,可以使用正常的实例化语法 (new在 C# 中,运算符New在 Visual Basic 中gcnewc + + 中)。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++). 如果在编译时不知道类型,则可以调用的非泛型重载CreateInstanceIf 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.

适用于