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[])

使用具名組件和無參數建構函式,建立具有已指定名稱的 COM 物件執行個體。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)

使用具名組件和無參數建構函式,建立具有已指定名稱的 COM 物件執行個體。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)

警告

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.

使用最符合指定參數的具名組件和建構函式,建立已在指定遠端網域中具有指定名稱之類型的執行個體。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);
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);
[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
[<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>]
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
Public Shared Function CreateInstance (domain As AppDomain, assemblyName As String, typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object(), securityAttributes As Evidence) As 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 type to create an instance of.

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.

傳回

ObjectHandle

必須解除包裝的控制代碼,用來存取新建立的執行個體。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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 不是空的陣列,而建立中的類型不是衍生自 MarshalByRefObjectactivationAttributes 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- 目前載入的是 Common Language Runtime (CLR) 2.0 版或更新版本,且已使用比目前載入之版本更新的 CLR 版本來編譯 assemblyNameThe 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.

備註

方法會 null 針對 Nullable<T> 沒有值的實例傳回。The method returns null for the Nullable<T> instances with no value.

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.

適用於

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);
[<System.Security.SecurityCritical>]
static member CreateInstance : AppDomain * string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (domain As AppDomain, assemblyName As String, typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object()) As 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 type to create an instance of.

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.

傳回

ObjectHandle

必須解除包裝的控制代碼,用來存取新建立的執行個體。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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 不是空的陣列,而建立中的類型不是衍生自 MarshalByRefObjectactivationAttributes 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- 目前載入的是 Common Language Runtime (CLR) 2.0 版或更新版本,且已使用比目前載入之版本更新的 CLR 版本來編譯 assemblyNameThe 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.

方法會 null 針對 Nullable<T> 沒有值的實例傳回。The method returns null for the Nullable<T> instances with no value.

用來解除包裝傳回 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.

適用於

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);
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
Public Shared Function CreateInstance (assemblyName As String, typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, 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 type to create an instance of.

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.

傳回

ObjectHandle

必須解除包裝的控制代碼,用來存取新建立的執行個體。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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 不是空的陣列,而建立中的類型不是衍生自 MarshalByRefObjectactivationAttributes 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- 目前載入的是 Common Language Runtime (CLR) 2.0 版或更新版本,且已使用比目前載入之版本更新的 CLR 版本來編譯 assemblyNameThe 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.

方法會 null 針對 Nullable<T> 沒有值的實例傳回。The method returns null for the Nullable<T> instances with no value.

注意

從 .NET Framework 2.0 Service Pack 1 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且包含非公用類型和成員之元件的授權集被限制為呼叫者的授權集或其子集,則可以使用這個方法來建立非公用類型和成員。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

適用於

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);
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
Public Shared Function CreateInstance (type As Type, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object()) As Object

參數

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.

傳回

Object

新建立之物件的參考。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 不是空的陣列,而建立中的類型不是衍生自 MarshalByRefObjectactivationAttributes 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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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.

方法會 null 針對 Nullable<T> 沒有值的實例傳回。The method returns null for the Nullable<T> instances with no value.

注意

從 .NET Framework 2.0 Service Pack 1 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且非公用類型和成員的授權集被限制為呼叫者的授權集或其子集,則可以使用這個方法來存取非公用類型和成員。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

適用於

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);
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
Public Shared Function CreateInstance (type As Type, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo) As Object

參數

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.

傳回

Object

新建立之物件的參考。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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.

方法會 null 針對 Nullable<T> 沒有值的實例傳回。The method returns null for the Nullable<T> instances with no value.

注意

從 .NET Framework 2.0 Service Pack 1 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且包含非公用類型和成員之元件的授權集被限制為呼叫者的授權集或其子集,則可以使用這個方法來存取非公用類型和成員。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

適用於

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);
public static object CreateInstance (Type type, object[] args, object[] activationAttributes);
static member CreateInstance : Type * obj[] * obj[] -> obj
Public Shared Function CreateInstance (type As Type, args As Object(), activationAttributes As Object()) As Object

參數

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.

傳回

Object

新建立之物件的參考。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 不是空的陣列,而建立中的類型不是衍生自 MarshalByRefObjectactivationAttributes 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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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.

方法會 null 針對 Nullable<T> 沒有值的實例傳回。The method returns null for the Nullable<T> instances with no value.

注意

從 .NET Framework 2.0 Service Pack 1 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且包含非公用類型的元件的授權集僅限於呼叫者的授權集或其子集,則可以使用這個方法來存取非公用類型。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

適用於

CreateInstance(String, String, Object[])

使用具名組件和無參數建構函式,建立具有已指定名稱的 COM 物件執行個體。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);
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 type to create an instance of.

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.

傳回

ObjectHandle

必須解除包裝的控制代碼,用來存取新建立的執行個體。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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 不是空的陣列,而建立中的類型不是衍生自 MarshalByRefObjectactivationAttributes 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- 目前載入的是 Common Language Runtime (CLR) 2.0 版或更新版本,且已使用比目前載入之版本更新的 CLR 版本來編譯 assemblyNameThe 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.

備註

方法會傳回 null 實例的 Nullable<T>The method returns null for the Nullable<T> instances.

用來解除包裝傳回 ObjectHandle.Unwrap 值。Use ObjectHandle.Unwrap to unwrap the return value.

注意

從 .NET Framework 2.0 Service Pack 1 開始,如果呼叫者已被授 ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess 旗標,且非公用類型的授權集限制為呼叫者的授權集或其子集,則可以使用這個方法來建立非公用類型。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

適用於

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

警告

Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

使用具名組件和最符合指定參數的建構函式,建立已具有指定名稱之類型的執行個體。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);
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);
[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
[<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.")>]
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
Public Shared Function CreateInstance (assemblyName As String, typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object(), securityInfo As Evidence) 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 type to create an instance of.

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.

傳回

ObjectHandle

必須解除包裝的控制代碼,用來存取新建立的執行個體。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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 不是空的陣列,而建立中的類型不是衍生自 MarshalByRefObjectactivationAttributes 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- 目前載入的是 Common Language Runtime (CLR) 2.0 版或更新版本,且已使用比目前載入之版本更新的 CLR 版本來編譯 assemblyNameThe 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.

備註

方法會 null 針對 Nullable<T> 沒有值的實例傳回。The method returns null for the Nullable<T> instances with no value.

用來解除包裝傳回 ObjectHandle.Unwrap 值。Use ObjectHandle.Unwrap to unwrap the return value.

注意

從 .NET Framework 2.0 Service Pack 1 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且包含非公用類型和成員之元件的授權集被限制為呼叫者的授權集或其子集,則可以使用這個方法來建立非公用類型和成員。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

適用於

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 System::Object ^ CreateInstance(Type ^ type, cli::array <System::Object ^> ^ args);
public static object CreateInstance (Type type, params object[] args);
public static object? CreateInstance (Type type, params object?[]? args);
public static object CreateInstance (Type type, object[] args);
static member CreateInstance : Type * obj[] -> obj
Public Shared Function CreateInstance (type As Type, ParamArray args As Object()) As Object
Public Shared Function CreateInstance (type As Type, args As Object()) As Object

參數

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.

傳回

Object

新建立之物件的參考。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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.

範例

下列範例會呼叫 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

下列範例會建立一個不規則陣列,其元素是要傳遞至函式的引數 StringThe 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.

方法會 null 針對 Nullable<T> 沒有值的實例傳回。The method returns null for the Nullable<T> instances with no value.

注意

從 .NET Framework 2.0 Service Pack 1 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且包含非公用類型的元件的授權集僅限於呼叫者的授權集或其子集,則可以使用這個方法來存取非公用類型。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

適用於

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);
public static object CreateInstance (Type type, bool nonPublic);
static member CreateInstance : Type * bool -> obj
Public Shared Function CreateInstance (type As Type, nonPublic As Boolean) As Object

參數

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.

傳回

Object

新建立之物件的參考。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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.

備註

方法會傳回 null 實例的 Nullable<T>The method returns null for the Nullable<T> instances.

注意

從 .NET Framework 2.0 Service Pack 1 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且包含非公用類型和成員之元件的授權集被限制為呼叫者的授權集或其子集,則可以使用這個方法來存取非公用類型和成員。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

適用於

CreateInstance(String, String)

使用具名組件和無參數建構函式,建立具有已指定名稱的 COM 物件執行個體。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);
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 type to create an instance of.

傳回

ObjectHandle

必須解除包裝的控制代碼,用來存取新建立的執行個體。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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- 目前載入的是 Common Language Runtime (CLR) 2.0 版或更新版本,且已使用比目前載入之版本更新的 CLR 版本來編譯 assemblyNameThe 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 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

備註

方法會傳回 null 實例的 Nullable<T>The method returns null for the Nullable<T> instances.

用來解除包裝傳回 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,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".

如需 common language runtime 如何識別和載入元件的詳細資訊,請參閱 執行時間如何找出元件。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 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且包含非公用類型的元件的授權集僅限於呼叫者的授權集或其子集,則可以使用這個方法來建立非公用類型。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

適用於

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
Public Shared Function CreateInstance (activationContext As ActivationContext, activationCustomData As String()) As 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.

傳回

ObjectHandle

必須解除包裝的控制代碼,用來存取新建立的物件。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);
public static object? CreateInstance (Type type);
static member CreateInstance : Type -> obj
Public Shared Function CreateInstance (type As Type) As Object

參數

type
Type

要建立之物件的類型。The type of object to create.

傳回

Object

新建立之物件的參考。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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.

範例

下列程式碼範例示範如何呼叫 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(Environment.NewLine + "Objects and their default values:" + Environment.NewLine)
        For Each o As Object In instlist
            Console.WriteLine("Type:     {0}" + Environment.NewLine + "Value:    {1}" + _
                Environment.NewLine + "HashCode: {2}" + Environment.NewLine, _
                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.

方法會傳回 null 實例的 Nullable<T>The method returns null for the Nullable<T> instances.

注意

從 .NET Framework 2.0 Service Pack 1 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且包含非公用類型的元件的授權集僅限於呼叫者的授權集或其子集,則可以使用這個方法來存取非公用類型。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

適用於

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
Public Shared Function CreateInstance (activationContext As ActivationContext) As ObjectHandle

參數

activationContext
ActivationContext

啟動內容物件,指定要建立的物件。An activation context object that specifies the object to create.

傳回

ObjectHandle

必須解除包裝的控制代碼,用來存取新建立的物件。A handle that must be unwrapped to access the newly created object.

備註

方法會傳回 null 實例的 Nullable<T>The method returns null for the Nullable<T> instances.

使用方法來解除包裝傳回 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);
public static System.Runtime.Remoting.ObjectHandle CreateInstance (AppDomain domain, string assemblyName, 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
[<System.Security.SecurityCritical>]
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 type to create an instance of.

傳回

ObjectHandle

必須解除包裝的控制代碼,用來存取新建立的執行個體。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.

無法建立抽象型別的執行個體 (Instance)。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.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。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- 目前載入的是 Common Language Runtime (CLR) 2.0 版或更新版本,且已使用比目前載入之版本更新的 CLR 版本來編譯 assemblyNameThe 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.

備註

方法會傳回 null 實例的 Nullable<T>The method returns null for the Nullable<T> instances.

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.

適用於

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.

例外狀況

無法建立抽象類別的執行個體,或為 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 # 的 (運算子使用一般具現化語法 gcnewIf 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.

適用於