且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建一个给定类型的实例?

更新时间:2023-11-30 14:07:46

最近的可用的Activator.CreateInstance$c$c>:

The closest available is Activator.CreateInstance:

object o = Activator.CreateInstance(type);

...但当然,这依赖于那里是一个公共参数的构造函数。 (其他重载允许您指定构造函数的参数。)

... but of course this relies on there being a public parameterless constructor. (Other overloads allow you to specify constructor arguments.)

我用显式类型变量在这里说清楚,我们真的没有该类型本身的变量...你不能写:

I've used an explicitly typed variable here to make it clear that we really don't have a variable of the type itself... you can't write:

Type t = typeof(MemoryStream);
// Won't compile
MemoryStream ms = Activator.CreateInstance(t);

例如。返回值的CreateInstance 的编译时类型总是对象

for example. The compile-time type of the return value of CreateInstance is always object.

注意默认(T)不会的创建一个引用类型的实例 - 它给出了类型,默认值是引用类型空引用。相比之下,与的CreateInstance 这实际上将创建一个新的对象。

Note that default(T) won't create an instance of a reference type - it gives the default value for the type, which is a null reference for reference types. Compare that with CreateInstance which would actually create a new object.