Difference between Assembly.CreateInstance and Activator.CreateInstance?

三世轮回 提交于 2019-12-17 18:35:07

问题


What is the difference between these calls?


回答1:


None. The Assembly.CreateInstance actually calls Activator.CreateInstance under the hood.

Using Reflector on 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);
}



回答2:


Assembly.CreateInstance looks for a type in a particular assembly, whereas Activator.CreateInstance can create an object of any type.

Activator.CreateInstance has overloads that Assembly doesn't; for instance, it can create objects in other app domains, or on another server using Remoting.




回答3:


You can supply Activator.CreateInstance with the name of the type and the name of the assembly instead of a Type object. This means it will try to load the assembly into the current AppDomain (if not currently loaded) and then attempt to load the type. I believe Assembly.CreateInstance (which does call Activator) does not attempt to load the assembly if it is not loaded. It simply attempts to get the Type object for the specified type and returns null if it is not found (I say this by reading code and not after testing).



来源:https://stackoverflow.com/questions/1833615/difference-between-assembly-createinstance-and-activator-createinstance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!