简体   繁体   English

Activator.CreateInstance()

[英]Activator.CreateInstance()

I've been using Activator.CreateInstance() in some of my codes. 我一直在我的一些代码中使用Activator.CreateInstance()。 Is there any risk to making an instance using this? 使用此实例创建实例是否有任何风险?

Well, there's the risk that your code is weakly typed, and you won't find out that you've accidentally tried to use it with a type which doesn't have a public parameterless constructor until execution time... and it's going to perform a bit worse than a direct constructor call. 好吧,你的代码是弱类型的风险,并且你不会发现你不小心尝试使用没有公共无参数构造函数的类型,直到执行时...它会发生执行比直接构造函数调用更糟糕。 Other than that, it should be okay. 除此之外,应该没问题。

If you can design around it to use strongly typed factories instead, that would be preferable in various ways - but I totally understand that that's not always appropriate. 如果你可以围绕它设计使用强类型工厂,那么这将以各种方式更好 - 但我完全理解这并不总是合适的。 Basically it should be a bit of a last recourse for when normal design patterns fail you, but it's a perfectly reasonable last recourse :) 基本上,当正常的设计模式让你失望时,它应该是一个最后的追索权,但它是一个完全合理的最后追索权:)

Do you have any specific concerns? 你有什么具体的顾虑吗?

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

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