调用 Activator.CreateInstance 有什么原因吗?
我正在维护其他人的代码,他们在方法中包含此部分:
object ReportCriteriaInstance =
Activator.CreateInstance(
typeof(MyCompany.Utils.ReportStructure.ReportSearchCriteria));
//ReportCriteria is passed in as a method parameter
ReportCriteriaInstance = ReportCriteria;
我不知道为什么他们在使用 CreateInstance() 实例化后一行将
。ReportCriteriaInstace
设置为不同的值
除此之外, 因为我们将已知类型传递给 CreateInstance
(MyCompany.Utils.ReportStructure.ReportSearchCriteria
),有什么理由不使用 new() 来代替?我可能没有得到一些默认的、无参数构造函数的原因?
I'm maintaining someone else's code and they have this section in a method:
object ReportCriteriaInstance =
Activator.CreateInstance(
typeof(MyCompany.Utils.ReportStructure.ReportSearchCriteria));
//ReportCriteria is passed in as a method parameter
ReportCriteriaInstance = ReportCriteria;
I don't know why they're setting ReportCriteriaInstace
to a different value one line after instantiating it with CreateInstance()
.
Aside from that,
because we're passing in a known type to CreateInstance
(MyCompany.Utils.ReportStructure.ReportSearchCriteria
) is there any reason not to use new() instead? Some default, parameterless constructor reason I'm not getting maybe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这似乎是为实现穷人的 DI 容器而放弃的努力。后来该对象刚刚传入,因此可以安全地删除代码(除非有一个默认的
ReportSearchCriteria
构造函数有一些潜在的副作用)。This seems like an abandoned effort to implement poor man's DI container. Later on the object was just passed in, so the code can be safely removed (unless there is a default
ReportSearchCriteria
constructor that has some potential side effects).您可以轻松地将代码转换为以下内容,完全避免重构的副作用:
You can easily convert code to the following, avoiding side effects of the refactorings entirely: