使用指定类型的默认构造函数来创建该类型的实例。
程序集: mscorlib(位于 mscorlib.dll 中)
异常 | 条件 |
---|---|
ArgumentNullException |
type 为 null。 |
ArgumentException |
type 不是 RuntimeType。 - 或 - type 是一个开放式泛型类型(即,ContainsGenericParameters 属性返回 true)。 |
NotSupportedException |
不支持创建 Void 和 RuntimeArgumentHandle 类型,也不支持创建这些类型的数组。 |
TargetInvocationException |
被调用的构造函数引发异常。 |
MethodAccessException |
调用方没有调用此构造函数的权限。 |
MemberAccessException |
无法创建抽象类的实例,或者用后期绑定机制调用了该成员。 |
MissingMethodException |
找不到匹配的公共构造函数。 |
COMException |
type 是一个 COM 对象,但用于获取类型的类标识符无效,或被标识的类未注册。 |
TypeLoadException |
type 不是有效的类型。 |
要调用的类型和构造函数必须是可访问的。如果使用 DynamicMethod 创建动态方法,则不能调用 internal 构造函数,因为该动态方法将承载在系统提供的程序集内的某个匿名模块中。
版本说明
Windows Phone
对于不具有未定义构造函数的类型,CreateInstance 方法引发 MemberAccessException 异常而不是MissingMethodException 异常。
下面的代码示例演示如何调用 CreateInstance(Type) 方法。此代码示例摘自一个为 Activator 类提供的更大示例。
Type sbType = typeof(StringBuilder); // Create an instance of the StringBuilder type using Activator.CreateInstance // and the parameterless constructor. object o = Activator.CreateInstance(sbType); // Append a string to the StringBuilder object and display the StringBuilder, // late bound. sbType.InvokeMember("Append", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, Type.DefaultBinder, o, new object[] {"Hello, there."}); outputBlock.Text += o.ToString() + "\n";