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