如何创建一个给定类型的实例? [英] How to create an instance for a given Type?

查看:185
本文介绍了如何创建一个给定类型的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用泛型,您可以

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?

推荐答案

最近的可用的<一个href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx"><$c$c>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.

这篇关于如何创建一个给定类型的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆