简体   繁体   中英

Difference between Assembly.CreateInstance and Activator.CreateInstance?

这些电话有什么区别?

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

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM