从类型得到一个新的对象实例实例、对象、类型

2023-09-02 20:41:52 作者:捕捉一只甜心

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:

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");