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)

警告

此 API 現已淘汰。

使用最符合指定參數的具名組件和建構函式,建立已在指定遠端網域中具有指定名稱之類型的執行個體。Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(AppDomain ^ domain, System::String ^ assemblyName, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes, System::Security::Policy::Evidence ^ securityAttributes);
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See https://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
[System.Security.SecurityCritical]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityAttributes);
static member CreateInstance : AppDomain * string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle

參數

domain
AppDomain

要在其中建立名稱為 typeName 之類型的網域。The domain where the type named typeName is created.

assemblyName
String

要在其中搜尋名稱為 typeName 之類型的組件名稱。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,則會搜尋執行中的組件。If assemblyName is null, the executing assembly is searched.

typeName
String

慣用類型的完整名稱。The fully qualified name of the preferred type.

ignoreCase
Boolean

true 指定 typeName 的搜尋不區分大小寫,false 指定搜尋區分大小寫。true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

bindingAttr
BindingFlags

零或多個位元旗標的組合,此位元旗標會影響 typeName 建構函式的搜尋。A combination of zero or more bit flags that affect the search for the typeName constructor. 如果 bindingAttr 為零,則會針對公用建構函式執行區分大小寫的搜尋。If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

物件,使用 bindingAttrargs 來搜尋及識別 typeName 建構函式。An object that uses bindingAttr and args to seek and identify the typeName constructor. 如果 bindernull,則會使用預設繫結器。If binder is null, the default binder is used.

args
Object[]

引數的陣列,此引數在數目、順序和類型上符合要叫用的建構函式的參數。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 是空陣列或 null,則會叫用未採用參數的建構函式 (無參數建構函式)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

culture
CultureInfo

特定文化特性的資訊,其可控制 args 到型式類型 (為 typeName 建構函式宣告) 的強制轉型。Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. 如果 culturenull,會使用目前執行緒的 CultureInfoIf culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

一或多個屬性的陣列,此屬性可參與啟動過程。An array of one or more attributes that can participate in activation. 這通常是包含單一 UrlAttribute 物件的陣列。This is typically an array that contains a single UrlAttribute object. UrlAttribute 會指定啟動遠端物件所需的 URL。The UrlAttribute specifies the URL that is required to activate a remote object.

securityAttributes
Evidence

用來執行安全性原則決策和授權程式碼使用權限的資訊。Information used to make security policy decisions and grant code permissions.

傳回

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

屬性

例外狀況

domaintypeNamenulldomain or typeName is null.

找不到相符的建構函式。No matching constructor was found.

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

找不到 assemblyNameassemblyName was not found.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

無法建立抽象類別的執行個體,或者這個成員曾被晚期繫結機制叫用過。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

透過反映叫用並擲回例外狀況的建構函式。The constructor, which was invoked through reflection, threw an exception.

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.

備註

當主機需要在具有限制安全性許可權的應用程式域中執行程式碼時,請使用 CreateInstanceUse CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

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

注意

這個方法會使用 SecurityAction.LinkDemand 要求立即呼叫端具有完全信任。This method uses SecurityAction.LinkDemand to require the immediate caller to have full trust.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
針對在所有類型成員上叫用作業的能力。for the ability to invoke operations on all type members. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

SecurityCriticalAttribute
需要完全信任立即呼叫者。requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

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

使用最符合指定參數的具名組件和建構函式,建立已在指定遠端網域中具有指定名稱之類型的執行個體。Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.

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

參數

domain
AppDomain

要在其中建立名稱為 typeName 之類型的網域。The domain where the type named typeName is created.

assemblyName
String

要在其中搜尋名稱為 typeName 之類型的組件名稱。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,則會搜尋執行中的組件。If assemblyName is null, the executing assembly is searched.

typeName
String

慣用類型的完整名稱。The fully qualified name of the preferred type.

ignoreCase
Boolean

true 指定 typeName 的搜尋不區分大小寫,false 指定搜尋區分大小寫。true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

bindingAttr
BindingFlags

零或多個位元旗標的組合,此位元旗標會影響 typeName 建構函式的搜尋。A combination of zero or more bit flags that affect the search for the typeName constructor. 如果 bindingAttr 為零,則會針對公用建構函式執行區分大小寫的搜尋。If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

物件,使用 bindingAttrargs 來搜尋及識別 typeName 建構函式。An object that uses bindingAttr and args to seek and identify the typeName constructor. 如果 bindernull,則會使用預設繫結器。If binder is null, the default binder is used.

args
Object[]

引數的陣列,此引數在數目、順序和類型上符合要叫用的建構函式的參數。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 是空陣列或 null,則會叫用未採用參數的建構函式 (無參數建構函式)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

culture
CultureInfo

特定文化特性的資訊,其可控制 args 到型式類型 (為 typeName 建構函式宣告) 的強制轉型。Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. 如果 culturenull,會使用目前執行緒的 CultureInfoIf culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

一或多個屬性的陣列,此屬性可參與啟動過程。An array of one or more attributes that can participate in activation. 陣列通常只會包含一個 UrlAttribute 物件來指定用以啟動遠端物件的 URL。This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

此參數與啟動了用戶端的物件相關。This parameter is related to client-activated objects. 用戶端啟動是一項舊的技術,保留目的在提供回溯相容性,不建議用於新的開發。Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. 分散式應用程式應該改用 Windows Communication Foundation。Distributed applications should instead use Windows Communication Foundation.

傳回

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

屬性

例外狀況

domaintypeNamenulldomain or typeName is null.

找不到相符的建構函式。No matching constructor was found.

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

找不到 assemblyNameassemblyName was not found.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

無法建立抽象類別的執行個體,或者這個成員曾被晚期繫結機制叫用過。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

透過反映叫用並擲回例外狀況的建構函式。The constructor, which was invoked through reflection, threw an exception.

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.

備註

當主機需要在具有限制安全性許可權的應用程式域中執行程式碼時,請使用 CreateInstanceUse CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

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

注意

這個方法會使用 SecurityAction.LinkDemand 要求立即呼叫端具有完全信任。This method uses SecurityAction.LinkDemand to require the immediate caller to have full trust.

安全性

SecurityCriticalAttribute
需要完全信任立即呼叫者。requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
針對在所有類型成員上叫用作業的能力。for the ability to invoke operations on all type members. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

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

使用具名組件和最符合指定參數的建構函式,建立已具有指定名稱之類型的執行個體。Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.

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

參數

assemblyName
String

要在其中搜尋名稱為 typeName 之類型的組件名稱。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,則會搜尋執行中的組件。If assemblyName is null, the executing assembly is searched.

typeName
String

慣用類型的完整名稱。The fully qualified name of the preferred type.

ignoreCase
Boolean

true 指定 typeName 的搜尋不區分大小寫,false 指定搜尋區分大小寫。true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

bindingAttr
BindingFlags

零或多個位元旗標的組合,此位元旗標會影響 typeName 建構函式的搜尋。A combination of zero or more bit flags that affect the search for the typeName constructor. 如果 bindingAttr 為零,則會針對公用建構函式執行區分大小寫的搜尋。If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

物件,使用 bindingAttrargs 來搜尋及識別 typeName 建構函式。An object that uses bindingAttr and args to seek and identify the typeName constructor. 如果 bindernull,則會使用預設繫結器。If binder is null, the default binder is used.

args
Object[]

引數的陣列,此引數在數目、順序和類型上符合要叫用的建構函式的參數。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 是空陣列或 null,則會叫用未採用參數的建構函式 (無參數建構函式)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

culture
CultureInfo

特定文化特性的資訊,其可控制 args 到型式類型 (為 typeName 建構函式宣告) 的強制轉型。Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. 如果 culturenull,會使用目前執行緒的 CultureInfoIf culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

一或多個屬性的陣列,此屬性可參與啟動過程。An array of one or more attributes that can participate in activation. 陣列通常只會包含一個 UrlAttribute 物件來指定用以啟動遠端物件的 URL。This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

此參數與啟動了用戶端的物件相關。This parameter is related to client-activated objects. 用戶端啟動是一項舊的技術,保留目的在提供回溯相容性,不建議用於新的開發。Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. 分散式應用程式應該改用 Windows Communication Foundation。Distributed applications should instead use Windows Communication Foundation.

傳回

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

例外狀況

typeNamenulltypeName is null.

找不到相符的建構函式。No matching constructor was found.

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

找不到 assemblyNameassemblyName was not found.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

無法建立抽象類別的執行個體,或者這個成員曾被晚期繫結機制叫用過。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

透過反映叫用並擲回例外狀況的建構函式。The constructor, which was invoked through reflection, threw an exception.

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.

注意

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1開始,如果呼叫者已被授與 ReflectionPermissionFlag.RestrictedMemberAccess 旗標 ReflectionPermission,而且包含非公用類型和成員之元件的授權集限制為呼叫者的,則這個方法可以用來建立非公用類型和成員。授與集或子集。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller's grant set or to a subset thereof. (請參閱反映的安全性考慮)。(See Security Considerations for Reflection.)

若要使用這項功能,您的應用程式應將目標設為 .NET Framework 3.5.NET Framework 3.5 (含) 以後版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用於存取非公用類型和成員,而不考慮其授與集。for accessing nonpublic types and members regardless of their grant set. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

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

使用最符合指定參數的建構函式,建立指定類型的執行個體。Creates an instance of the specified type using the constructor that best matches the specified parameters.

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

參數

type
Type

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

bindingAttr
BindingFlags

零或多個位元旗標的組合,此位元旗標會影響 type 建構函式的搜尋。A combination of zero or more bit flags that affect the search for the type constructor. 如果 bindingAttr 為零,則會針對公用建構函式執行區分大小寫的搜尋。If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

物件,使用 bindingAttrargs 來搜尋及識別 type 建構函式。An object that uses bindingAttr and args to seek and identify the type constructor. 如果 bindernull,則會使用預設繫結器。If binder is null, the default binder is used.

args
Object[]

引數的陣列,此引數在數目、順序和類型上符合要叫用的建構函式的參數。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 是空陣列或 null,則會叫用未採用參數的建構函式 (無參數建構函式)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

culture
CultureInfo

特定文化特性的資訊,其可控制 args 到型式類型 (為 type 建構函式宣告) 的強制轉型。Culture-specific information that governs the coercion of args to the formal types declared for the type constructor. 如果 culturenull,會使用目前執行緒的 CultureInfoIf culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

一或多個屬性的陣列,此屬性可參與啟動過程。An array of one or more attributes that can participate in activation. 陣列通常只會包含一個 UrlAttribute 物件來指定用以啟動遠端物件的 URL。This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

此參數與啟動了用戶端的物件相關。This parameter is related to client-activated objects. 用戶端啟動是一項舊的技術,保留目的在提供回溯相容性,不建議用於新的開發。Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. 分散式應用程式應該改用 Windows Communication Foundation。Distributed applications should instead use Windows Communication Foundation.

傳回

新建立物件的參考。A reference to the newly created object.

例外狀況

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-或--or- type 是開放式泛型類型 (也就是 ContainsGenericParameters 屬性會傳回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不可以是 TypeBuildertype cannot be a TypeBuilder.

-或--or- 不支援建立 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 類型或這些類型的陣列。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-或--or- activationAttributes 不是空的陣列,而建立中的類型不是衍生自 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.

注意

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1開始,如果呼叫者已被授與 ReflectionPermissionFlag.RestrictedMemberAccess 旗標 ReflectionPermission,而且非公用類型和成員的授權集受限於呼叫者的授與集或子集 thereo,這個方法就可以用來存取非公用類型和成員。f.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the nonpublic types and members is restricted to the caller's grant set or to a subset thereof. (請參閱反映的安全性考慮)。(See Security Considerations for Reflection.)

若要使用這項功能,您的應用程式應將目標設為 .NET Framework 3.5.NET Framework 3.5 (含) 以後版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
提供辨識項。for supplying evidence. 相關聯的列舉: ControlEvidenceAssociated enumeration: ControlEvidence

ReflectionPermission
用於存取非公用類型和成員,而不考慮其授與集。for accessing nonpublic types and members regardless of their grant set. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

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

使用最符合指定參數的建構函式,建立指定類型的執行個體。Creates an instance of the specified type using the constructor that best matches the specified parameters.

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

參數

type
Type

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

bindingAttr
BindingFlags

零或多個位元旗標的組合,此位元旗標會影響 type 建構函式的搜尋。A combination of zero or more bit flags that affect the search for the type constructor. 如果 bindingAttr 為零,則會針對公用建構函式執行區分大小寫的搜尋。If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

物件,使用 bindingAttrargs 來搜尋及識別 type 建構函式。An object that uses bindingAttr and args to seek and identify the type constructor. 如果 bindernull,則會使用預設繫結器。If binder is null, the default binder is used.

args
Object[]

引數的陣列,此引數在數目、順序和類型上符合要叫用的建構函式的參數。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 是空陣列或 null,則會叫用未採用參數的建構函式 (無參數建構函式)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

culture
CultureInfo

特定文化特性的資訊,其可控制 args 到型式類型 (為 type 建構函式宣告) 的強制轉型。Culture-specific information that governs the coercion of args to the formal types declared for the type constructor. 如果 culturenull,會使用目前執行緒的 CultureInfoIf culture is null, the CultureInfo for the current thread is used.

傳回

新建立物件的參考。A reference to the newly created object.

例外狀況

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-或--or- type 是開放式泛型類型 (也就是 ContainsGenericParameters 屬性會傳回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不可以是 TypeBuildertype cannot be a TypeBuilder.

-或--or- 不支援建立 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 類型或這些類型的陣列。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-或--or- 包含 type 的組件是以 Save 建立的動態組件。The assembly that contains type is a dynamic assembly that was created with Save.

-或--or- 最符合 args 的建構函式有 varargs 引數。The constructor that best matches args has varargs arguments.

正在呼叫的建構函式擲回例外狀況。The constructor being called throws an exception.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

無法建立抽象類別的執行個體,或者這個成員曾被晚期繫結機制叫用過。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

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.

注意

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1開始,如果呼叫者已被授與 ReflectionPermissionFlag.RestrictedMemberAccess 旗標 ReflectionPermission,而且包含非公用類型和成員之元件的授權集限制為呼叫者的,則這個方法可以用來存取非公用類型和成員。授與集或子集。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller's grant set or to a subset thereof. (請參閱反映的安全性考慮)。(See Security Considerations for Reflection.)

若要使用這項功能,您的應用程式應將目標設為 .NET Framework 3.5.NET Framework 3.5 (含) 以後版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用於存取非公用類型和成員,而不考慮其授與集。for accessing nonpublic types and members regardless of their grant set. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

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

使用最符合指定參數的建構函式,建立指定類型的執行個體。Creates an instance of the specified type using the constructor that best matches the specified parameters.

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

參數

type
Type

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

args
Object[]

引數的陣列,此引數在數目、順序和類型上符合要叫用的建構函式的參數。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 是空陣列或 null,則會叫用未採用參數的建構函式 (無參數建構函式)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

activationAttributes
Object[]

一或多個屬性的陣列,此屬性可參與啟動過程。An array of one or more attributes that can participate in activation. 陣列通常只會包含一個 UrlAttribute 物件來指定用以啟動遠端物件的 URL。This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

此參數與啟動了用戶端的物件相關。This parameter is related to client-activated objects. 用戶端啟動是一項舊的技術,保留目的在提供回溯相容性,不建議用於新的開發。Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. 分散式應用程式應該改用 Windows Communication Foundation。Distributed applications should instead use Windows Communication Foundation.

傳回

新建立物件的參考。A reference to the newly created object.

例外狀況

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-或--or- type 是開放式泛型類型 (也就是 ContainsGenericParameters 屬性會傳回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不可以是 TypeBuildertype cannot be a TypeBuilder.

-或--or- 不支援建立 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 類型或這些類型的陣列。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-或--or- activationAttributes 不是空的陣列,而建立中的類型不是衍生自 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.

注意

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1開始,如果呼叫者已被授與 ReflectionPermissionFlag.RestrictedMemberAccess 旗標 ReflectionPermission,而且包含非公用類型之元件的授權集僅限於呼叫者的授與集或子集,這個方法就可以用來存取非公用類型。reof.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller's grant set or to a subset thereof. (請參閱反映的安全性考慮)。(See Security Considerations for Reflection.)

若要使用這項功能,您的應用程式應將目標設為 .NET Framework 3.5.NET Framework 3.5 (含) 以後版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用於存取非公用類型,不論其授與集為何。for accessing nonpublic types regardless of their grant set. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(String, String, Object[])

使用具名組件和無參數建構函式,建立具有已指定名稱的 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);
static member CreateInstance : string * string * obj[] -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (assemblyName As String, typeName As String, activationAttributes As Object()) As ObjectHandle

參數

assemblyName
String

要在其中搜尋名稱為 typeName 之類型的組件名稱。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,則會搜尋執行中的組件。If assemblyName is null, the executing assembly is searched.

typeName
String

慣用類型的完整名稱。The fully qualified name of the preferred type.

activationAttributes
Object[]

一或多個屬性的陣列,此屬性可參與啟動過程。An array of one or more attributes that can participate in activation. 陣列通常只會包含一個 UrlAttribute 物件來指定用以啟動遠端物件的 URL。This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

此參數與啟動了用戶端的物件相關。This parameter is related to client-activated objects. 用戶端啟動是一項舊的技術,保留目的在提供回溯相容性,不建議用於新的開發。Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. 分散式應用程式應該改用 Windows Communication Foundation。Distributed applications should instead use Windows Communication Foundation.

傳回

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

例外狀況

typeNamenulltypeName is null.

找不到相符的公用建構函式。No matching public constructor was found.

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

找不到 assemblyNameassemblyName was not found.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

無法建立抽象類別的執行個體,或者這個成員曾被晚期繫結機制叫用過。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

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.

備註

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

注意

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1開始,如果呼叫者已被授與 ReflectionPermissionFlag.RestrictedMemberAccess 旗標 ReflectionPermission,而且非公用類型的授權集僅限於呼叫者的授與集或其子集,則可以使用這個方法來建立非公用類型。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the nonpublic types is restricted to the caller's grant set or to a subset thereof. (請參閱反映的安全性考慮)。(See Security Considerations for Reflection.)

若要使用這項功能,您的應用程式應將目標設為 .NET Framework 3.5.NET Framework 3.5 (含) 以後版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用於存取非公用類型,不論其授與集為何。for accessing nonpublic types regardless of their grant set. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

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

警告

此 API 現已淘汰。

使用具名組件和最符合指定參數的建構函式,建立已具有指定名稱之類型的執行個體。Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(System::String ^ assemblyName, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes, System::Security::Policy::Evidence ^ securityInfo);
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See https://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityInfo);
static member CreateInstance : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle

參數

assemblyName
String

要在其中搜尋名稱為 typeName 之類型的組件名稱。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,則會搜尋執行中的組件。If assemblyName is null, the executing assembly is searched.

typeName
String

慣用類型的完整名稱。The fully qualified name of the preferred type.

ignoreCase
Boolean

true 指定 typeName 的搜尋不區分大小寫,false 指定搜尋區分大小寫。true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

bindingAttr
BindingFlags

零或多個位元旗標的組合,此位元旗標會影響 typeName 建構函式的搜尋。A combination of zero or more bit flags that affect the search for the typeName constructor. 如果 bindingAttr 為零,則會針對公用建構函式執行區分大小寫的搜尋。If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

物件,使用 bindingAttrargs 來搜尋及識別 typeName 建構函式。An object that uses bindingAttr and args to seek and identify the typeName constructor. 如果 bindernull,則會使用預設繫結器。If binder is null, the default binder is used.

args
Object[]

引數的陣列,此引數在數目、順序和類型上符合要叫用的建構函式的參數。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 是空陣列或 null,則會叫用未採用參數的建構函式 (無參數建構函式)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

culture
CultureInfo

特定文化特性的資訊,其可控制 args 到型式類型 (為 typeName 建構函式宣告) 的強制轉型。Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. 如果 culturenull,會使用目前執行緒的 CultureInfoIf culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

一或多個屬性的陣列,此屬性可參與啟動過程。An array of one or more attributes that can participate in activation. 陣列通常只會包含一個 UrlAttribute 物件來指定用以啟動遠端物件的 URL。This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

此參數與啟動了用戶端的物件相關。This parameter is related to client-activated objects. 用戶端啟動是一項舊的技術,保留目的在提供回溯相容性,不建議用於新的開發。Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. 分散式應用程式應該改用 Windows Communication Foundation。Distributed applications should instead use Windows Communication Foundation.

securityInfo
Evidence

用來執行安全性原則決策和授權程式碼使用權限的資訊。Information used to make security policy decisions and grant code permissions.

傳回

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

屬性

例外狀況

typeNamenulltypeName is null.

找不到相符的建構函式。No matching constructor was found.

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

找不到 assemblyNameassemblyName was not found.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

無法建立抽象類別的執行個體,或者這個成員曾被晚期繫結機制叫用過。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

透過反映叫用並擲回例外狀況的建構函式。The constructor, which was invoked through reflection, threw an exception.

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.

注意

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1開始,如果呼叫者已被授與 ReflectionPermissionFlag.RestrictedMemberAccess 旗標 ReflectionPermission,而且包含非公用類型和成員之元件的授權集限制為呼叫者的,則這個方法可以用來建立非公用類型和成員。授與集或子集。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller's grant set or to a subset thereof. (請參閱反映的安全性考慮)。(See Security Considerations for Reflection.)

若要使用這項功能,您的應用程式應將目標設為 .NET Framework 3.5.NET Framework 3.5 (含) 以後版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用於存取非公用類型和成員,而不考慮其授與集。for accessing nonpublic types and members regardless of their grant set. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(Type, Object[])

使用最符合指定參數的建構函式,建立指定類型的執行個體。Creates an instance of the specified type using the constructor that best matches the specified parameters.

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

參數

type
Type

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

args
Object[]

引數的陣列,此引數在數目、順序和類型上符合要叫用的建構函式的參數。An array of arguments that match in number, order, and type the parameters of the constructor to invoke. 如果 args 是空陣列或 null,則會叫用未採用參數的建構函式 (無參數建構函式)。If args is an empty array or null, the constructor that takes no parameters (the parameterless constructor) is invoked.

傳回

新建立物件的參考。A reference to the newly created object.

例外狀況

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-或--or- type 是開放式泛型類型 (也就是 ContainsGenericParameters 屬性會傳回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不可以是 TypeBuildertype cannot be a TypeBuilder.

-或--or- 不支援建立 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 類型或這些類型的陣列。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-或--or- 包含 type 的組件是以 Save 建立的動態組件。The assembly that contains type is a dynamic assembly that was created with Save.

-或--or- 最符合 args 的建構函式有 varargs 引數。The constructor that best matches args has varargs arguments.

正在呼叫的建構函式擲回例外狀況。The constructor being called throws an exception.

適用於 Windows 市集應用程式的 .NET 或是可攜式類別庫中,改為攔截基底類別例外狀況MemberAccessExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

無法建立抽象類別的執行個體,或者這個成員曾被晚期繫結機制叫用過。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

適用於 Windows 市集應用程式的 .NET 或是可攜式類別庫中,改為攔截基底類別例外狀況MissingMemberExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MissingMemberException, instead.

找不到相符的公用建構函式。No matching public constructor was found.

type 是 COM 物件,但用來取得類型的類別識別項無效,或已識別的類別未經登錄。type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

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

範例

下列範例會呼叫 CreateInstance(Type, Object[]) 方法,以建立 String 物件。The following example calls the CreateInstance(Type, Object[]) method to create a String object. 它會呼叫 String.String(Char[], Int32, Int32) 的函式,以具現化字串,其中包含從第十四個位置開始之字元陣列中的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開始,如果呼叫者已被授與 ReflectionPermissionFlag.RestrictedMemberAccess 旗標 ReflectionPermission,而且包含非公用類型之元件的授權集僅限於呼叫者的授與集或子集,這個方法就可以用來存取非公用類型。reof.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller's grant set or to a subset thereof. (請參閱反映的安全性考慮)。(See Security Considerations for Reflection.)

若要使用這項功能,您的應用程式應將目標設為 .NET Framework 3.5.NET Framework 3.5 (含) 以後版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用於存取非公用類型,不論其授與集為何。for accessing nonpublic types regardless of their grant set. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(Type, Boolean)

使用所指定類型的無參數建構函式,建立該類型的執行個體。Creates an instance of the specified type using that type's parameterless constructor.

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

參數

type
Type

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

nonPublic
Boolean

如果公用或非公用無參數建構函式可相符,則為 true;如果只有公用無參數建構函式可相符,則為 falsetrue if a public or nonpublic parameterless constructor can match; false if only a public parameterless constructor can match.

傳回

新建立物件的參考。A reference to the newly created object.

例外狀況

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-或--or- type 是開放式泛型類型 (也就是 ContainsGenericParameters 屬性會傳回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不可以是 TypeBuildertype cannot be a TypeBuilder.

-或--or- 不支援建立 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 類型或這些類型的陣列。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-或--or- 包含 type 的組件是以 Save 建立的動態組件。The assembly that contains type is a dynamic assembly that was created with Save.

正在呼叫的建構函式擲回例外狀況。The constructor being called throws an exception.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

無法建立抽象類別的執行個體,或者這個成員曾被晚期繫結機制叫用過。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

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.

備註

注意

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1開始,如果呼叫者已被授與 ReflectionPermissionFlag.RestrictedMemberAccess 旗標 ReflectionPermission,而且包含非公用類型和成員之元件的授權集限制為呼叫者的,則這個方法可以用來存取非公用類型和成員。授與集或子集。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller's grant set or to a subset thereof. (請參閱反映的安全性考慮)。(See Security Considerations for Reflection.)

若要使用這項功能,您的應用程式應將目標設為 .NET Framework 3.5.NET Framework 3.5 (含) 以後版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用於存取非公用類型和成員,而不考慮其授與集。for accessing nonpublic types and members regardless of their grant set. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(String, String)

使用具名組件和無參數建構函式,建立具有已指定名稱的 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);
static member CreateInstance : string * string -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (assemblyName As String, typeName As String) As ObjectHandle

參數

assemblyName
String

要在其中搜尋名稱為 typeName 之類型的組件名稱。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,則會搜尋執行中的組件。If assemblyName is null, the executing assembly is searched.

typeName
String

慣用類型的完整名稱。The fully qualified name of the preferred type.

傳回

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

例外狀況

typeNamenulltypeName is null.

找不到相符的公用建構函式。No matching public constructor was found.

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

找不到 assemblyNameassemblyName was not found.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

您無法建立抽象類別的執行個體,或者這個成員曾被晚期繫結機制叫用過。You cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

透過反映叫用並擲回例外狀況的建構函式。The constructor, which was invoked through reflection, threw an exception.

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.

範例

下列範例會在名為 PersonInfo的元件中定義名為 Person 的類別。The following example defines a class named Person in an assembly named PersonInfo. 請注意,Person 類別有兩個參數,其中一個是無參數的。Note that the Person class has two constructors, one of which is parameterless.

using System;

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

下列範例會呼叫 CreateInstance(String, String) 方法,將 Person 類別具現化。The following example calls the CreateInstance(String, String) method to instantiate the Person class. 它需要將 PersonInfo 的參考加入至專案。It requires a reference to PersonInfo.dll to be added to the project. 因為 CreateInstance(String, String) 方法會呼叫 Person 類別無參數的函式,所以這個範例會將值指派給其 Name 屬性。Because the CreateInstance(String, String) method calls the Person class parameterless constructor, the example assigns a value to its Name property.

using System;
using System.Runtime.Remoting;

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

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

不過,通常會呼叫 CreateInstance 來具現化跨越機器界限的型別,或在設計階段未知的類型。However, CreateInstance is frequently called to instantiate a type that crosses machine boundaries or that is not known at design time. 在此情況下,您不能在專案中包含元件的參考,也無法對類型的成員進行早期繫結的呼叫。In this case, you cannot include a reference to the assembly in the project and cannot make early-bound calls to the type's members. 為了解決這項限制,下列範例會使用 CreateInstance 方法和反映,將值指派給 Person 物件的 Name 屬性,並顯示其值。To work around this limitation, the following example uses the CreateInstance method along with reflection to assign a value to the Person object's Name property and to display its value.

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

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

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

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

備註

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

assemblyName 可以是下列其中一項:assemblyName can be either of the following:

  • 元件的簡單名稱,不含其路徑或副檔名。The simple name of an assembly, without its path or file extension. 例如,您可以為 .\bin\TypeExtensions.dll. 其路徑和名稱的元件指定 TypeExtensionsFor example, you would specify TypeExtensions for an assembly whose path and name are .\bin\TypeExtensions.dll.

  • 已簽署元件的完整名稱,由其簡單名稱、版本、文化特性和公開金鑰標記組成;例如,"TypeExtensions,Version = 1.0.0.0,Culture = 中性,PublicKeyToken = 181869f2f7435b51"。The full name of a signed assembly, which consists of its simple name, version, culture, and public key token; for example, "TypeExtensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=181869f2f7435b51".

如需 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.NET Framework 2.0 Service Pack 1開始,如果呼叫者已被授與 ReflectionPermissionFlag.RestrictedMemberAccess 旗標 ReflectionPermission,而且包含非公用類型之元件的授權集僅限於呼叫者的授與集或子集,這個方法就可以用來建立非公用類型。reof.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller's grant set or to a subset thereof. (請參閱反映的安全性考慮)。(See Security Considerations for Reflection.)

若要使用這項功能,您的應用程式應將目標設為 .NET Framework 3.5.NET Framework 3.5 (含) 以後版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用於存取非公用類型,不論其授與集為何。for accessing nonpublic types regardless of their grant set. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(ActivationContext, String[])

建立類型的執行個體,這個類型是由指定的 ActivationContext 物件所指派,並且是以指定的自訂啟動資料所啟動。Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data.

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

參數

activationContext
ActivationContext

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

activationCustomData
String[]

Unicode 字串的陣列,包含自訂啟動資料。An array of Unicode strings that contain custom activation data.

傳回

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

備註

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

啟用內容會在以資訊清單為基礎的啟用期間使用,以設定網域原則並提供以應用程式為基礎的安全性模型。The activation context is used during manifest-based activation to set up the domain policy and to provide an application-based security model. ActivationContext 類別包含可存取應用程式資訊清單的 ApplicationIdentity 物件。The ActivationContext class contains an ApplicationIdentity object that provides access to the application manifest. 如需詳細資訊,請參閱 ApplicationSecurityManager 類別。For more information, see the ApplicationSecurityManager class.

另請參閱

CreateInstance(Type)

使用所指定類型的無參數建構函式,建立該類型的執行個體。Creates an instance of the specified type using that type's parameterless constructor.

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

參數

type
Type

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

傳回

新建立物件的參考。A reference to the newly created object.

例外狀況

typenulltype is null.

type 不是 RuntimeTypetype is not a RuntimeType.

-或--or- type 是開放式泛型類型 (也就是 ContainsGenericParameters 屬性會傳回 true)。type is an open generic type (that is, the ContainsGenericParameters property returns true).

type 不可以是 TypeBuildertype cannot be a TypeBuilder.

-或--or- 不支援建立 TypedReferenceArgIteratorVoidRuntimeArgumentHandle 類型或這些類型的陣列。Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-或--or- 包含 type 的組件是以 Save 建立的動態組件。The assembly that contains type is a dynamic assembly that was created with Save.

正在呼叫的建構函式擲回例外狀況。The constructor being called throws an exception.

適用於 Windows 市集應用程式的 .NET 或是可攜式類別庫中,改為攔截基底類別例外狀況MemberAccessExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

無法建立抽象類別的執行個體,或者這個成員曾被晚期繫結機制叫用過。Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

COM 類型不是透過 GetTypeFromProgIDGetTypeFromCLSID 取得。The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

適用於 Windows 市集應用程式的 .NET 或是可攜式類別庫中,改為攔截基底類別例外狀況MissingMemberExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MissingMemberException, instead.

找不到相符的公用建構函式。No matching public constructor was found.

type 是 COM 物件,但用來取得類型的類別識別項無效,或已識別的類別未經登錄。type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

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

範例

下列程式碼範例示範如何呼叫 CreateInstance(Type) 方法。The following code example demonstrates how to call the CreateInstance(Type) method. 系統會建立數個不同類型的實例,並顯示其預設值。Instances of several different types are created and their default values are displayed.

using namespace System;

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

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

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

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

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

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

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

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

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

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

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

備註

要叫用的函式必須是可存取的。The constructor to be invoked must be accessible.

注意

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1開始,如果呼叫者已被授與 ReflectionPermissionFlag.RestrictedMemberAccess 旗標 ReflectionPermission,而且包含非公用類型之元件的授權集僅限於呼叫者的授與集或子集,這個方法就可以用來存取非公用類型。reof.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller's grant set or to a subset thereof. (請參閱反映的安全性考慮)。(See Security Considerations for Reflection.)

若要使用這項功能,您的應用程式應將目標設為 .NET Framework 3.5.NET Framework 3.5 (含) 以後版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
用於存取非公用類型,不論其授與集為何。for accessing nonpublic types regardless of their grant sets. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

CreateInstance(ActivationContext)

建立類型的執行個體,這個類型是由指定的 ActivationContext 物件所指派。Creates an instance of the type designated by the specified ActivationContext object.

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

參數

activationContext
ActivationContext

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

傳回

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

備註

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

啟用內容會在以資訊清單為基礎的啟用期間使用,以設定網域原則並提供以應用程式為基礎的安全性模型。The activation context is used during manifest-based activation to set up the domain policy and to provide an application-based security model. ActivationContext 類別包含可存取應用程式資訊清單的 ApplicationIdentity 物件。The ActivationContext class contains an ApplicationIdentity object that provides access to the application manifest. 如需詳細資訊,請參閱 ApplicationSecurityManager 類別。For more information, see the ApplicationSecurityManager class.

另請參閱

CreateInstance(AppDomain, String, String)

使用具名組件和無參數建構函式,建立已在指定遠端網域中具有指定名稱的類型執行個體。Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and parameterless constructor.

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

參數

domain
AppDomain

建立名稱為 typeName 之類型的遠端網域。The remote domain where the type named typeName is created.

assemblyName
String

要在其中搜尋名稱為 typeName 之類型的組件名稱。The name of the assembly where the type named typeName is sought. 如果 assemblyNamenull,則會搜尋執行中的組件。If assemblyName is null, the executing assembly is searched.

typeName
String

慣用類型的完整名稱。The fully qualified name of the preferred type.

傳回

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

屬性

例外狀況

typeNamedomainnulltypeName or domain is null.

找不到相符的公用建構函式。No matching public constructor was found.

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

找不到 assemblyNameassemblyName was not found.

呼叫端沒有呼叫這個建構函式的權限。The caller does not have permission to call this constructor.

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

備註

當主機需要在具有限制安全性許可權的應用程式域中執行程式碼時,請使用 CreateInstanceUse CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

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

注意

這個方法會使用 SecurityAction.LinkDemand 要求立即呼叫端具有完全信任。This method uses SecurityAction.LinkDemand to require the immediate caller to have full trust.

安全性

SecurityPermission
在建立委派的實例時,能夠呼叫非受控碼。for the ability to call unmanaged code when creating an instance of a delegate. 相關聯的列舉: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
針對在所有類型成員上叫用作業的能力。for the ability to invoke operations on all type members. 相關聯的列舉: MemberAccessAssociated enumeration: MemberAccess

SecurityCriticalAttribute
需要完全信任立即呼叫者。requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

CreateInstance<T>()

使用無參數建構函式,建立由指定之泛型類型參數所指定之類型的執行個體。Creates an instance of the type designated by the specified generic type parameter, using the parameterless constructor.

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

類型參數

T

要建立的類型。The type to create.

傳回

T

新建立物件的參考。A reference to the newly created object.

例外狀況

適用於 Windows 市集應用程式的 .NET 或是可攜式類別庫中,改為攔截基底類別例外狀況MissingMemberExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MissingMemberException, instead.

無法建立抽象類別的執行個體,或為 T 指定的類型沒有無參數的建構函式。Cannot create an instance of an abstract class, or the type that is specified for T does not have a parameterless constructor.

備註

編譯器會使用 CreateInstance<T>() 泛型方法來執行類型參數所指定之類型的具現化。The CreateInstance<T>() generic method is used by compilers to implement the instantiation of types specified by type parameters. 例如,在下列泛型方法中,new T() 的執行(在中C++為gcnew T())會使用 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 運算子,Visual Basic 中的 New C++,gcnew 在中)。If the type is known at compile time, normal instantiation syntax can be used (new operator in C#, New in Visual Basic, gcnew in C++). 如果在編譯時期不知道型別,您可以呼叫 CreateInstance的非泛型多載。If the type is not known at compile time, you can call a non-generic overload of CreateInstance.

因為 CreateInstance 的非泛型多載已經提供晚期繫結的函式解析,所以沒有 CreateInstance<T>() 泛型方法的多載接受引數清單。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.

適用於