在构造函数外C#对象的构造 [英] C# Object construction outside the constructor

查看:125
本文介绍了在构造函数外C#对象的构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当谈到他们之间设计类和沟通,我总是试图在这样的方式来设计他们所有的对象构造和组合发生在对象的构造函数。我不喜欢对象的构造和成分正在发生的来自外部的想法,像其他对象设置属性和调用我的对象上的方法进行初始化。这尤其变得丑陋当多个对象尝试做thisto你的对象,你永远不知道以什么顺序你props\methods将被执行。



Unforunatly我stumbl在这种情况很多时候,尤其是现在dependecy注入框架的日益普及,许多库和框架依靠某种外部对象初始化,而且经常需要我们的对象,但物业注射过于不仅构造函数注入。



我的问题是:




  1. 它是确定有对象relly的某些方法,或将号召他们财产之后,他们可以考虑他们initialzied?


  2. 是疗法某种的情况下模式的时候你的对象的演技接收器,而且必须支持叫它多个接口,并且这些调用的顺序并不重要? (东西比设置标志,如ThisWasDone,ThatWasCalled更好)



解决方案

它是确定有这种relly的某些方法或属性对他们被称为对象后,他们可以考虑他们initialzied?




没有。初始化方法是一种痛苦,因为没有保证,他们将被调用。一个简单的解决方案是切换到接口和使用的工厂或生成器模式组成的实施



@马克塞曼写了一篇关于它:的 http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx




是否有某种模式的情况下,当你的对象的演技接收器,而且必须支持叫它多个接口,并且这些调用的顺序也没关系吗? (东西比设置标志,如ThisWasDone,ThatWasCalled更好)




Builder模式。


When it comes to designing classes and "communication" between them, I always try to design them in such way that all object construction and composing take place in object constructor. I don't like the idea of object construction and composition taking place from outside, like other objects setting properties and calling methods on my object to initialize it. This especially gets ugly when multiple object try to do thisto your object and you never know in what order your props\methods will be executed.

Unforunatly I stumbl on such situations quite often, especially now with the growing popularity of dependecy injection frameworks, lots of libraries and frameworks rely on some kind of external object initialization, and quite often require not only constructor injection on our object but property injection too.

My question are:

  1. Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?

  2. Is ther some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)

解决方案

Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?

No. Init methods are a pain since there is no guarantee that they will get called. A simple solution is to switch to interfaces and use factory or builder pattern to compose the implementation.

@Mark Seemann has written a article about it: http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx

Is there some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)

Builder pattern.

这篇关于在构造函数外C#对象的构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆