【发布时间】:2009-12-02 15:26:57
【问题描述】:
这些调用之间有什么区别?
【问题讨论】:
标签: c# reflection assemblies
这些调用之间有什么区别?
【问题讨论】:
标签: c# reflection assemblies
没有。 Assembly.CreateInstance 实际上在底层调用了 Activator.CreateInstance。
在 Assembly.CreateInstance 上使用反射器:
public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
Type type = this.GetType(typeName, false, ignoreCase);
if (type == null)
{
return null;
}
return Activator.CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes);
}
【讨论】:
Assembly.CreateInstance 在特定程序集中查找类型,而Activator.CreateInstance 可以创建任何类型的对象。
Activator.CreateInstance 具有 Assembly 没有的重载;例如,它可以在其他应用程序域中创建对象,或者使用 Remoting 在另一台服务器上创建对象。
【讨论】:
您可以为Activator.CreateInstance 提供类型名称和程序集名称,而不是类型对象。这意味着它将尝试将程序集加载到当前 AppDomain(如果当前未加载),然后尝试加载该类型。我相信 Assembly.CreateInstance (它确实调用了 Activator)不会尝试加载未加载的程序集。它只是尝试获取指定类型的 Type 对象,如果找不到则返回 null (我是通过阅读代码而不是在测试后说的)。
【讨论】: