添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft Edge More info about Internet Explorer and Microsoft Edge 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.

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

Parameters

NotSupportedException

Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject .

The constructor that best matches args has varargs arguments.

Remarks

The method returns null for the Nullable<T> instances with no value.

Use CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

Use ObjectHandle.Unwrap to unwrap the return value.

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

Parameters

An array of one or more attributes that can participate in activation. 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. Distributed applications should instead use Windows Communication Foundation.

Returns

NotSupportedException

Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject .

The constructor that best matches args has varargs arguments.

Remarks

Use CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

The method returns null for the Nullable<T> instances with no value.

Use ObjectHandle.Unwrap to unwrap the return value.

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

Parameters

An array of one or more attributes that can participate in activation. 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. Distributed applications should instead use Windows Communication Foundation.

Returns

NotSupportedException

Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject .

The constructor that best matches args has varargs arguments.

Remarks

Use ObjectHandle.Unwrap to unwrap the return value.

The method returns null for the Nullable<T> instances with no value.

Starting with .NET Framework 2.0, 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 .) To use this functionality, your application should target .NET Framework 3.5 or later.

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

Parameters

An array of one or more attributes that can participate in activation. 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. Distributed applications should instead use Windows Communication Foundation.

Returns

type cannot be a TypeBuilder .

Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject .

The assembly that contains type is a dynamic assembly that was created with Save .

The constructor that best matches args has varargs arguments.

Remarks

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.

The method returns null for the Nullable<T> instances with no value.

Starting with .NET Framework 2.0, 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 .) To use this functionality, your application should target .NET Framework 3.5 or later.

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

Parameters

Culture-specific information that governs the coercion of args to the formal types declared for the type constructor. If culture is null , the CultureInfo for the current thread is used.

Returns

type cannot be a TypeBuilder .

Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

The assembly that contains type is a dynamic assembly that was created with Save .

The constructor that best matches args has varargs arguments.

Remarks

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.

The method returns null for the Nullable<T> instances with no value.

Starting with .NET Framework 2.0, 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 .) To use this functionality, your application should target .NET Framework 3.5 or later.

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

Parameters

An array of one or more attributes that can participate in activation. 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. Distributed applications should instead use Windows Communication Foundation.

Returns

type cannot be a TypeBuilder .

Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject .

The assembly that contains type is a dynamic assembly that was created with Save .

The constructor that best matches args has varargs arguments.

Remarks

The constructor to be invoked must be accessible and must provide the most specific match with the specified argument list.

The method returns null for the Nullable<T> instances with no value.

Starting with .NET Framework 2.0, 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 .) To use this functionality, your application should target .NET Framework 3.5 or later.

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

Parameters

An array of one or more attributes that can participate in activation. 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. Distributed applications should instead use Windows Communication Foundation.

Returns

NotSupportedException

Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject .

activationAttributes is not a UrlAttribute

array.

Remarks

The method returns null for the Nullable<T> instances.

Use ObjectHandle.Unwrap to unwrap the return value.

Starting with .NET Framework 2.0, 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 .) To use this functionality, your application should target .NET Framework 3.5 or later.

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

Parameters

An array of one or more attributes that can participate in activation. 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. Distributed applications should instead use Windows Communication Foundation.

NotSupportedException

Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject .

The constructor that best matches args has varargs arguments.

Remarks

The method returns null for the Nullable<T> instances with no value.

Use ObjectHandle.Unwrap to unwrap the return value.

Starting with .NET Framework 2.0, 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 .) To use this functionality, your application should target .NET Framework 3.5 or later.

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

Parameters

An array of arguments that match in number, order, and type the parameters of the constructor to invoke. If args is an empty array or null , the constructor that takes no parameters (the parameterless constructor) is invoked.

Returns

type cannot be a TypeBuilder .

Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

The assembly that contains type is a dynamic assembly that was created with Save .

The constructor that best matches args has varargs arguments.

Examples

The following example calls the CreateInstance(Type, Object[]) method to create a String object. 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 open System // Initialize array of characters from a to z. let chars = [| 'a' .. 'z' |] let obj = Activator.CreateInstance(typeof<string>, chars[13..22]) printfn $"{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) 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

The following example creates a jagged array whose elements are arguments to be passed to a String constructor. 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 open System let chars = [| 'a' .. 'f' |] let arguments = [| chars chars[1..4] Array.create 20 chars[1] |] for args in arguments do let result = Activator.CreateInstance(typeof<string>, args) printfn $"{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) End Sub End Module ' The example displays the following output: ' String: abcdef ' String: bcde ' String: bbbbbbbbbbbbbbbbbbbb

Remarks

The constructor to be invoked must be accessible and must provide the most specific match with the specified argument list.

The method returns null for the Nullable<T> instances with no value.

Starting with .NET Framework 2.0, 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 .) To use this functionality, your application should target .NET Framework 3.5 or later.

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

Parameters

true if a public or nonpublic parameterless constructor can match; false if only a public parameterless constructor can match.

Returns

type cannot be a TypeBuilder .

Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

The assembly that contains type is a dynamic assembly that was created with Save .

Starting with .NET Framework 2.0, 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 .) To use this functionality, your application should target .NET Framework 3.5 or later.

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

Parameters

Examples

The following example defines a class named Person in an assembly named PersonInfo . 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; type Person(name) = member val Name = name with get, set override this.ToString() = this.Name new () = Person Unchecked.defaultof<string> 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 Return Me._name End Get Me._name = value End Set End Property Public Overrides Function ToString() As String Return Me._name End Function End Class

The following example calls the CreateInstance(String, String) method to instantiate the Person class. It requires a reference to PersonInfo.dll to be added to the project. 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 open System let handle = Activator.CreateInstance("PersonInfo", "Person") let p = handle.Unwrap() :?> Person p.Name <- "Samuel" printfn $"{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

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. 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 open System let handle = Activator.CreateInstance("PersonInfo", "Person") let p = handle.Unwrap() let t = p.GetType() let prop = t.GetProperty "Name" if not (isNull prop) then prop.SetValue(p, "Samuel") let method = t.GetMethod "ToString" let retVal = method.Invoke(p, null) if not (isNull retVal) then printfn $"{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

Remarks

The method returns null for the Nullable<T> instances.

Use ObjectHandle.Unwrap to unwrap the return value.

assemblyName can be either of the following:

  • The simple name of an assembly, without its path or file extension. For example, you would specify TypeExtensions for an assembly whose path and name are .\bin\TypeExtensions.dll.

  • The full name of a signed assembly, which consists of its simple name, version, culture, and public key token; for example, "TypeExtensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=181869f2f7435b51".

    For more information on how the common language runtime identifies and loads assemblies, see How the Runtime Locates Assemblies . For information on using the application configuration file to define assembly locations, see Specifying an Assembly's Location . If assemblyName is found, it is loaded in the default context.

    Starting with .NET Framework 2.0, 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 .) To use this functionality, your application should target .NET Framework 3.5 or later.

    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

    Parameters

    Remarks

    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. The ActivationContext class contains an ApplicationIdentity object that provides access to the application manifest. For more information, see the ApplicationSecurityManager class.

    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

    Parameters

    type cannot be a TypeBuilder .

    Creation of TypedReference , ArgIterator , Void , and RuntimeArgumentHandle types, or arrays of those types, is not supported.

    The assembly that contains type is a dynamic assembly that was created with Save .

    Examples

    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 open System let instanceSpec = "System.EventArgs;System.Random;System.Exception;System.Object;System.Version" let instances = instanceSpec.Split ';' let instlist = Array.zeroCreate instances.Length let mutable item = obj () for i = 0 to instances.Length - 1 do // create the object from the specification string printfn $"Creating instance of: {instances.[i]}" item <- Activator.CreateInstance(Type.GetType instances.[i]) instlist.[i] <- item printfn "\nObjects and their default values:\n" for o in instlist do printfn $"Type: {o.GetType().FullName}\nValue: {o}\nHashCode: {o.GetHashCode()}\n" // 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

    Remarks

    The constructor to be invoked must be accessible.

    The method returns null for the Nullable<T> instances.

    Starting with .NET Framework 2.0, 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 .) To use this functionality, your application should target .NET Framework 3.5 or later.

    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

    Parameters

    Remarks

    The method returns null for the Nullable<T> instances.

    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. The ActivationContext class contains an ApplicationIdentity object that provides access to the application manifest. For more information, see the ApplicationSecurityManager class.

    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

    Parameters

    Remarks

    The method returns null for the Nullable<T> instances.

    Use CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

    Use ObjectHandle.Unwrap to unwrap the return value.

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

    Type Parameters

    MissingMethodException

    Cannot create an instance of an abstract class, or the type that is specified for T does not have a parameterless constructor.

    Note: In .NET for Windows Store apps or the Portable Class Library , catch the base class exception, MissingMemberException , instead.

    Remarks

    The CreateInstance<T>() generic method is used by compilers to implement the instantiation of types specified by type parameters. 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(); let factory<'T when 'T : (new: unit -> 'T)> = new 'T() Public Shared Function Factory(Of T As New)() As T Return New T() End Function

    In general, there is no use for the CreateInstance<T>() generic method in application code, because the type must be known at compile time. 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++). If the type is not known at compile time, you can call a non-generic overload of 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.

  •