从类型得到一个新的对象实例 [英] Get a new object instance from a Type

查看:155
本文介绍了从类型得到一个新的对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1未必总是知道一个对象在编译时的类型,但可能需要创建类型的一个实例。你如何从一个类型得到一个新的对象实例?

One may not always know the Type of an object at compile-time, but may need to create an instance of the Type. How do you get a new object instance from a Type?

推荐答案

激活中的类根系统命名空间是pretty的强大。

The Activator class within the root System namespace is pretty powerful.

有很多重载的传递参数​​的构造函数和这样的。退房文档:

There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at:

<一个href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx">http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

下面是一些简单的例子:

Here are some simple examples:

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

ObjectType instance = (ObjectType)Activator.CreateInstance("MyNamespace.ObjectType, MyAssembly");

这篇关于从类型得到一个新的对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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