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

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

问题描述

应该在构造函数中执行可能需要一些时间的操作,还是应该构造对象然后稍后初始化.

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.

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

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天全站免登陆