Uređivanje

Dijeli putem


Assembly.CreateInstance Method

Definition

Locates a type from this assembly and creates an instance of it using the system activator.

Overloads

CreateInstance(String)

Locates the specified type from this assembly and creates an instance of it using the system activator, using case-sensitive search.

CreateInstance(String, Boolean)

Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search.

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

Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search and having the specified culture, arguments, and binding and activation attributes.

CreateInstance(String)

Source:
Assembly.cs
Source:
Assembly.cs
Source:
Assembly.cs

Locates the specified type from this assembly and creates an instance of it using the system activator, using case-sensitive search.

public:
 System::Object ^ CreateInstance(System::String ^ typeName);
public:
 virtual System::Object ^ CreateInstance(System::String ^ typeName);
public object? CreateInstance (string typeName);
public object CreateInstance (string typeName);
member this.CreateInstance : string -> obj
abstract member CreateInstance : string -> obj
override this.CreateInstance : string -> obj
Public Function CreateInstance (typeName As String) As Object

Parameters

typeName
String

The FullName of the type to locate.

Returns

An instance of the specified type created with the parameterless constructor; or null if typeName is not found. The type is resolved using the default binder, without specifying culture or activation attributes, and with BindingFlags set to Public or Instance.

Implements

Exceptions

typeName is an empty string ("") or a string beginning with a null character.

-or-

The current assembly was loaded into the reflection-only context.

typeName is null.

No matching constructor was found.

typeName requires a dependent assembly that could not be found.

typeName requires a dependent assembly that was found but could not be loaded.

-or-

The current assembly was loaded into the reflection-only context, and typeName requires a dependent assembly that was not preloaded.

typeName requires a dependent assembly, but the file is not a valid assembly for the currently loaded runtime.

Examples

The following example defines a Person class and calls the CreateInstance(String) method to instantiate it.

using System;
using System.Reflection;
using Contoso.Libraries;

namespace Contoso.Libraries
{
   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 Example
{
   public static void Main()
   {
      Assembly assem = typeof(Person).Assembly;
      Person p = (Person) assem.CreateInstance("Contoso.Libraries.Person");
      if (! (p == null)) {
         p.Name = "John";
         Console.WriteLine("Instantiated a {0} object whose value is '{1}'",
                           p.GetType().Name, p);
      }
      else {
         Console.WriteLine("Unable to instantiate a Person object.");
      }
   }
}
// The example displays the following output:
//        Instantiated a Person object whose value is 'John'
Imports System.Reflection
Imports Contoso.Libraries

Namespace Contoso.Libraries
   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
End Namespace 

Module Example
   Public Sub Main()
      Dim assem As Assembly = GetType(Person).Assembly
      Dim p As Person = CType(assem.CreateInstance("Contoso.Libraries.Person"),
                              Person)
      If p IsNot Nothing Then
         p.Name = "John"
         Console.WriteLine("Instantiated a {0} object whose value is '{1}'",
                           p.GetType().Name, p)
      Else
         Console.WriteLine("Unable to instantiate a Person object.")
      End If   
   End Sub
End Module
' The example displays the following output:
'       Instantiated a Person object whose value is 'John'

Remarks

If the runtime is unable to find typeName in the Assembly instance, it returns null instead of throwing an exception. This might happen because:

  • You haven't specified the fully qualified name of the type.

  • You've specified the fully qualified type name, but its case doesn't match the case of the type's Type.FullName property. For a case-insensitive comparison of typeName with the type's full name, call the CreateInstance(String, Boolean) overload and specify true for the ignoreCase argument.

  • The type doesn't exist in the current Assembly instance.

Applies to

CreateInstance(String, Boolean)

Source:
Assembly.cs
Source:
Assembly.cs
Source:
Assembly.cs

Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search.

public:
 System::Object ^ CreateInstance(System::String ^ typeName, bool ignoreCase);
public:
 virtual System::Object ^ CreateInstance(System::String ^ typeName, bool ignoreCase);
public object? CreateInstance (string typeName, bool ignoreCase);
public object CreateInstance (string typeName, bool ignoreCase);
member this.CreateInstance : string * bool -> obj
abstract member CreateInstance : string * bool -> obj
override this.CreateInstance : string * bool -> obj
Public Function CreateInstance (typeName As String, ignoreCase As Boolean) As Object

Parameters

typeName
String

The FullName of the type to locate.

ignoreCase
Boolean

true to ignore the case of the type name; otherwise, false.

Returns

An instance of the specified type created with the parameterless constructor; or null if typeName is not found. The type is resolved using the default binder, without specifying culture or activation attributes, and with BindingFlags set to Public or Instance.

Implements

Exceptions

typeName is an empty string ("") or a string beginning with a null character.

-or-

The current assembly was loaded into the reflection-only context.

No matching constructor was found.

typeName is null.

typeName requires a dependent assembly that could not be found.

typeName requires a dependent assembly that was found but could not be loaded.

-or-

The current assembly was loaded into the reflection-only context, and typeName requires a dependent assembly that was not preloaded.

typeName requires a dependent assembly, but the file is not a valid assembly for the currently loaded runtime.

Examples

The following example defines a Person class. It then calls the CreateInstance(String) method to instantiate it, but because the casing of the typeName argument doesn't match that of the type's FullName property, the method returns null. When the example passes the same string to the CreateInstance(String, Boolean) overload and specifies that the comparison should be case-insensitive, the Person class is found, and a Person object is successfully instantiated.

using System;
using System.Reflection;
using Contoso.Libraries;

namespace Contoso.Libraries
{
   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 Example
{
   public static void Main()
   {
      String fullName = "contoso.libraries.person";
      Assembly assem = typeof(Person).Assembly;
      Person p = (Person) assem.CreateInstance(fullName);
      if (! (p == null)) {
         p.Name = "John";
         Console.WriteLine("Instantiated a {0} object whose value is '{1}'",
                           p.GetType().Name, p);
      }
      else {
         Console.WriteLine("Unable to instantiate a Person object " +
                           "with Assembly.CreateInstance(String)");
         // Try case-insensitive type name comparison.
         p = (Person) assem.CreateInstance(fullName, true);
         if (! (p == null)) {
            p.Name = "John";
            Console.WriteLine("Instantiated a {0} object whose value is '{1}'",
                              p.GetType().Name, p);
         }
         else {
            Console.WriteLine("Unable to instantiate a {0} object.",
                              fullName);
         }
      }
   }
}
// The example displays the following output:
//    Unable to instantiate a Person object with Assembly.CreateInstance(String)
//    Instantiated a Person object whose value is 'John'
Imports System.Reflection
Imports Contoso.Libraries

Namespace Contoso.Libraries
   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
End Namespace 

Module Example
   Public Sub Main()
      Dim fullName As String = "contoso.libraries.person"
      Dim assem As Assembly = GetType(Person).Assembly
      Dim p As Person = CType(assem.CreateInstance(fullName),
                              Person)
      If p IsNot Nothing Then
         p.Name = "John"
         Console.WriteLine("Instantiated a {0} object whose value is '{1}'",
                           p.GetType().Name, p)
      Else
         Console.WriteLine("Unable to instantiate a Person object" +
                           "with Assembly.CreateInstance(String)")
         ' Try case-insensitive type name comparison.
         p = CType(assem.CreateInstance(fullName, true), Person)
         If p IsNot Nothing Then 
            p.Name = "John"
            Console.WriteLine("Instantiated a {0} object whose value is '{1}'",
                              p.GetType().Name, p)
         Else 
            Console.WriteLine("Unable to instantiate a {0} object.", 
                              fullName)
         End If   
      End If   
   End Sub
End Module
' The example displays the following output:
'    Unable to instantiate a Person object with Assembly.CreateInstance(String)
'    Instantiated a Person object whose value is 'John'

Remarks

If the runtime is unable to find typeName in the Assembly instance, it returns null instead of throwing an exception. This might happen because:

  • You haven't specified the fully qualified name of the type.

  • The type doesn't exist in the current Assembly instance.

Applies to

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

Source:
Assembly.cs
Source:
Assembly.cs
Source:
Assembly.cs

Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search and having the specified culture, arguments, and binding and activation attributes.

public:
 virtual System::Object ^ CreateInstance(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 virtual object? CreateInstance (string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object[]? args, System.Globalization.CultureInfo? culture, object[]? activationAttributes);
public virtual object CreateInstance (string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
public object CreateInstance (string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
abstract member CreateInstance : string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> obj
override this.CreateInstance : string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> obj
Public Overridable Function CreateInstance (typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object()) As Object
Public Function CreateInstance (typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object()) As Object

Parameters

typeName
String

The FullName of the type to locate.

ignoreCase
Boolean

true to ignore the case of the type name; otherwise, false.

bindingAttr
BindingFlags

A bitmask that affects the way in which the search is conducted. The value is a combination of bit flags from BindingFlags.

binder
Binder

An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects via reflection. If binder is null, the default binder is used.

args
Object[]

An array that contains the arguments to be passed to the constructor. This array of arguments must match in number, order, and type the parameters of the constructor to be invoked. If the parameterless constructor is desired, args must be an empty array or null.

culture
CultureInfo

An instance of CultureInfo used to govern the coercion of types. If this is null, the CultureInfo for the current thread is used. (This is necessary to convert a string that represents 1000 to a Double value, for example, since 1000 is represented differently by different cultures.)

activationAttributes
Object[]

An array of one or more attributes that can participate in activation. 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

An instance of the specified type, or null if typeName is not found. The supplied arguments are used to resolve the type, and to bind the constructor that is used to create the instance.

Implements

Exceptions

typeName is an empty string ("") or a string beginning with a null character.

-or-

The current assembly was loaded into the reflection-only context.

typeName is null.

No matching constructor was found.

A non-empty activation attributes array is passed to a type that does not inherit from MarshalByRefObject.

typeName requires a dependent assembly that could not be found.

typeName requires a dependent assembly that was found but could not be loaded.

-or-

The current assembly was loaded into the reflection-only context, and typeName requires a dependent assembly that was not preloaded.

typeName requires a dependent assembly, but the file is not a valid assembly for the currently loaded runtime.

Applies to