简体   繁体   中英

Usage of Activator.CreateInstance()

What is actually the difference between the below two code snippets?

Object o = Activator.CreateInstance(typeof(StringBuilder));

StringBuilder sb = (StringBuilder) o;

and

StringBuilder sb = new StringBuilder();

From a practical point of view. There is no difference.

However, from a technical point of view. The first will incur a substantial performance penalty.

First, from the Activator.CreateInstance , since this is a Reflection call.

Then another performance hit when you cast object to StringBuilder .

From a design point of view however. Activator.CreateInstance takes Type as a parameter...

This means you can do the following...

public IStringBuilder ActivateStringBuilder(Type builderType)
{
     return (IStringBuilder) Activator.CreateInstance(builderType);
}

Ignoring that there is no such thing as IStringBuilder the above code allows you to, at runtime, change the behavior of the code, by passing in different Type s that implement IStringBuilder .

This is the basis for Dependency Injection (although, we tend to use much more complicated mechanisms to get around the performance issues I pointed out).

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