使用泛型,您可以
var object = default(T);
但是,当你已经是一个类型的实例我只能
But when all you have is a Type instance I could only
constructor = type.GetConstructor(Type.EmptyTypes);
var parameters = new object[0];
var obj = constructor.Invoke(parameters);
甚至
var obj = type.GetConstructor(Type.EmptyTypes).Invoke(new object[0]);
还没有一个较短的方式,像仿制药版本?
Isn't there a shorter way, like the generics version?
最近的可用的Activator.CreateInstance:
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.