在构造函数中应该做多少工作? [英] How much work should be done in a constructor?

查看:273
本文介绍了在构造函数中应该做多少工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可能需要一些时间的操作在构造函数中执行,或者应该构造对象,然后再初始化。

Should operations that could take some time be performed in a constructor or should the object be constructed and then initialised later.

例如,当构造一个表示目录结构应该在构造函数中完成对象及其子对象的填充。显然,一个目录可以包含目录,而这个目录又可以包含目录等。

For example when constructing an object that represents a directory structure should the population of the object and its children be done in the constructor. Clearly, a directory can contain directories and which in turn can contain directories and so on.

这个优雅的解决方案是什么?

What is the elegant solution to this?

推荐答案

历史上,我已经编码了我的构造函数,以便一旦构造函数方法完成,对象就可以使用。

Historically, I have coded my constructors so that the object is ready to use once the constructor method is complete. How much or how little code is involved depends on the requirements for the object.

例如,我需要在详细信息视图中显示以下公司类:

For example, let's say I need to display the following Company class in a details view:

public class Company
{
    public int Company_ID { get; set; }
    public string CompanyName { get; set; }
    public Address MailingAddress { get; set; }
    public Phones CompanyPhones { get; set; }
    public Contact ContactPerson { get; set; }
}



因为我想显示我在公司的所有信息详细信息视图,我的构造函数将包含填充每个属性所需的所有代码。鉴于这是一个复杂类型,公司构造函数将触发地址,电话和联系人构造函数的执行。

Since I want to display all the information I have about the company in the details view, my constructor will contain all of the code necessary to populate every property. Given that is a complex type, the Company constructor will trigger the execution of the Address, Phones and Contact constructor as well.

现在,如果我填充目录列表视图,其中我可能只需要CompanyName和主电话号码,我可能有一个第二个构造函数的类,只检索该信息,并留下其余信息为空我可能只是创建一个单独的对象只保留该信息。

Now, if I am populating a directory listing view, where I may only need the CompanyName and the main phone number, I may have a second constructor on the class that only retrieves that information and leaves the remaining information empty, or I may just create a separate object that only holds that information. It really just depends on how the information is retrieved, and from where.

不管类中的构造函数的数量,我个人的目标是做任何必要的处理以准备对象,以便对其施加任何任务。

Regardless of the number of constructors on a class, my personal goal is to do whatever processing is necessary to prepare the object for whatever tasks may be imposed upon it.

这篇关于在构造函数中应该做多少工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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