Assembly.CreateInstance Assembly.CreateInstance Assembly.CreateInstance Assembly.CreateInstance Method

定义

从此程序集中查找某个类型,然后使用系统激活器创建它的实例。Locates a type from this assembly and creates an instance of it using the system activator.

重载

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

使用区分大小写的搜索,从此程序集中查找指定的类型,然后使用系统激活器创建它的实例。Locates the specified type from this assembly and creates an instance of it using the system activator, using case-sensitive search.

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

参数

typeName
String String String String

要查找类型的 FullNameThe FullName of the type to locate.

返回

使用无参数构造函数创建的指定类型的实例;如果未找到 typeName,则为 nullAn instance of the specified type created with the parameterless constructor; or null if typeName is not found. 该类型使用默认联编程序解析,而无需指定区域性或激活属性,并将 BindingFlags 设置为 PublicInstanceThe type is resolved using the default binder, without specifying culture or activation attributes, and with BindingFlags set to Public or Instance.

实现

异常

typeName 为空字符串 ("") 或以空字符开头的字符串。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 所需的从属程序集无法找到。typeName requires a dependent assembly that could not be found.

typeName 所需的从属程序集已找到,但无法加载。typeName requires a dependent assembly that was found but could not be loaded.

- 或 --or- 当前程序集被加载到仅反射上下文中,并且 typeName 所需的从属程序集未预先加载。The current assembly was loaded into the reflection-only context, and typeName requires a dependent assembly that was not preloaded.

typeName 需要一个从属程序集,但该文件不是有效的程序集。typeName requires a dependent assembly, but the file is not a valid assembly.

-or- typeName 需要一个从属程序集,该程序集已针对比当前加载的版本更高的运行时版本进行了编译。typeName requires a dependent assembly that was compiled for a version of the runtime that is later than the currently loaded version.

示例

下面的示例定义了Person一个类, 并CreateInstance(String)调用了方法对其进行实例化。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'

注解

如果运行时Assembly在实例中找typeName不到, 则返回null , 而不是引发异常。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.

  • 已指定完全限定的类型名称, 但其大小写与类型的Type.FullName属性的大小写不匹配。You've specified the fully qualified type name, but its case doesn't match the case of the type's Type.FullName property. 对于类型的完整名称不区分typeName大小写的比较, 请CreateInstance(String, Boolean)调用ignoreCase重载, 并为参数true指定。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.

  • 当前Assembly实例中不存在该类型。The type doesn't exist in the current Assembly instance.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess

CreateInstance(String, Boolean) CreateInstance(String, Boolean) CreateInstance(String, Boolean) 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.

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

参数

typeName
String String String String

要查找类型的 FullNameThe FullName of the type to locate.

ignoreCase
Boolean Boolean Boolean Boolean

如果为 true,则忽略类型名的大小写;否则,为 falsetrue to ignore the case of the type name; otherwise, false.

返回

使用无参数构造函数创建的指定类型的实例;如果未找到 typeName,则为 nullAn instance of the specified type created with the parameterless constructor; or null if typeName is not found. 该类型使用默认联编程序解析,而无需指定区域性或激活属性,并将 BindingFlags 设置为 PublicInstanceThe type is resolved using the default binder, without specifying culture or activation attributes, and with BindingFlags set to Public or Instance.

实现

异常

typeName 为空字符串 ("") 或以空字符开头的字符串。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 所需的从属程序集无法找到。typeName requires a dependent assembly that could not be found.

typeName 所需的从属程序集已找到,但无法加载。typeName requires a dependent assembly that was found but could not be loaded.

- 或 --or- 当前程序集被加载到仅反射上下文中,并且 typeName 所需的从属程序集未预先加载。The current assembly was loaded into the reflection-only context, and typeName requires a dependent assembly that was not preloaded.

typeName 需要一个从属程序集,但该文件不是有效的程序集。typeName requires a dependent assembly, but the file is not a valid assembly.

-or- typeName 需要一个从属程序集,该程序集已针对比当前加载的版本更高的运行时版本进行了编译。typeName requires a dependent assembly that was compiled for a version of the runtime that is later than the currently loaded version.

示例

下面的示例定义了Person一个类。The following example defines a Person class. 然后, 它调用CreateInstance(String)方法对其进行实例化, 但由于typeName参数的大小写与类型的FullName属性的大小写不匹配, 因此null该方法返回。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. 当示例将同一字符串传递到CreateInstance(String, Boolean)重载, 并指定该比较应区分大小写时Person , 将找到该类, 并且Person已成功实例化对象。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'

注解

如果运行时Assembly在实例中找typeName不到, 则返回null , 而不是引发异常。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.

  • 当前Assembly实例中不存在该类型。The type doesn't exist in the current Assembly instance.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess

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

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);
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

参数

typeName
String String String String

要查找类型的 FullNameThe FullName of the type to locate.

ignoreCase
Boolean Boolean Boolean Boolean

如果为 true,则忽略类型名的大小写;否则,为 falsetrue to ignore the case of the type name; otherwise, false.

bindingAttr
BindingFlags BindingFlags BindingFlags BindingFlags

影响执行搜索的方式的位掩码。A bitmask that affects the way in which the search is conducted. 此值是 BindingFlags中的位标志的组合。The value is a combination of bit flags from BindingFlags.

binder
Binder Binder Binder Binder

一个对象,它启用绑定、对参数类型的强制、对成员的调用,以及通过反射对 MemberInfo 对象的检索。An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects via reflection. 如果 bindernull,则使用默认联编程序。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. 如果需要无参数构造函数,则 args 必须是空数组或 nullIf the parameterless constructor is desired, args must be an empty array or null.

culture
CultureInfo CultureInfo CultureInfo CultureInfo

用于控制类型强制的 CultureInfo 的实例。An instance of CultureInfo used to govern the coercion of types. 如果这是 null,则使用当前线程的 CultureInfoIf this is null, the CultureInfo for the current thread is used. (例如,这对于将表示 1000 的 String 转换为 Double 值是必需的,因为不同的区域性以不同的方式表示 1000。)(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. 通常,为包含单个 UrlAttribute 对象的数组,该对象指定激活远程对象所需的 URL。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.

返回

如果未找到 null,则为指定的类型实例或 typeNameAn 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.

实现

异常

typeName 为空字符串 ("") 或以空字符开头的字符串。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.

非空激活属性数组被传递给不是继承自 MarshalByRefObject 的类型。A non-empty activation attributes array is passed to a type that does not inherit from MarshalByRefObject.

typeName 所需的从属程序集无法找到。typeName requires a dependent assembly that could not be found.

typeName 所需的从属程序集已找到,但无法加载。typeName requires a dependent assembly that was found but could not be loaded.

-or- 当前程序集被加载到仅反射上下文中,并且 typeName 所需的从属程序集未预先加载。The current assembly was loaded into the reflection-only context, and typeName requires a dependent assembly that was not preloaded.

typeName 需要一个从属程序集,但该文件不是有效的程序集。typeName requires a dependent assembly, but the file is not a valid assembly.

-or- typeName 需要一个从属程序集,该程序集已针对比当前加载的版本更高的运行时版本进行了编译。typeName requires a dependent assembly which that was compiled for a version of the runtime that is later than the currently loaded version.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess

SecurityPermission
创建委托的实例。to create an instance of a delegate. 关联的枚举:UnmanagedCodeAssociated enumeration: UnmanagedCode

适用于