简体   繁体   English

Activator.CreateInstance() 的用法

[英]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.首先,来自Activator.CreateInstance ,因为这是一个反射调用。

Then another performance hit when you cast object to StringBuilder .然后,当您将objectStringBuilder时,另一个性能受到影响。

From a design point of view however.然而,从设计的角度来看。 Activator.CreateInstance takes Type as a parameter... Activator.CreateInstanceType作为参数...

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 .忽略没有IStringBuilder之类的东西,上面的代码允许您在运行时通过传入实现IStringBuilder的不同Type来更改代码的行为。

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).这是依赖注入的基础(尽管我们倾向于使用更复杂的机制来解决我指出的性能问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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