![](/img/trans.png)
[英]what is the difference between AppDomain.CreateInstance and Activator.CreateInstance?
[英]What is the difference between Activator.CreateInstance and a standard constructor?
使用Activator.CreateInstance
可以创建对象,即使无法直接访问它应属于的类(例如Reflection),也可以例如创建与另一个对象相同类型的对象:
var duplicate = Activator.CreateInstance(original.GetType());
如果您不完全了解原始对象的类,那么这是不可能的。
如果您知道将在设计时实例化的类型,则无需使用Activator.CreateInstance
。 Activator.CreateInstance
所做的全部工作就是调用公共默认构造函数。
Activator.CreateInstance
是“后期绑定”的一种形式,如果您要实例化在设计时不知道的Type
,它可能会很有用。 如果您已经在设计时知道具体类的类型,那么您肯定要使用“早期绑定”实例化它,它的速度更快,更简单,更明显。 即直接调用适当的构造函数。
Activator.CreatInstance将调用类Foo的默认构造函数。
唯一的区别是,如果您先于类型知道了类型,则使用new
的类型创建它会更有意义(且更易读)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.