初始化()与构造()方法,在对象创建正确使用 [英] Initialize() vs Constructor() method, proper usage on object creation

查看:120
本文介绍了初始化()与构造()方法,在对象创建正确使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道之间的差异构造和用户定义的初始化()根本方法。

We all know the difference between a Constructor and a User-Defined Initialize() method fundamentally.

我的问题是专注于为对象创建最佳设计实践。我们可以把所有的初始化()代码到构造函数(),反之亦然(将所有热身代码初始化方法,并呼吁从构造)这个方法。

My question is focused on best design practice for object creation. We can put all Initialize() code into Constructor() and vice versa (move all warm-up code to Initialize method and call this method from Constructor).

目前,设计一个新的类,我里面创建的任何新的实例构造函数()和移动任何其他热身代码到初始化()方法。

Currently, designing a new class, I create any new instances inside constructor() and move any other warm-up code into Initialize() method.

什么是您认为的最佳平衡点?

What's the best trade-off point in your opinion?

推荐答案

我觉得是应该考虑多个方面的内容:

I think there are multiple aspects that should be taken into consideration:


  • 一个构造函数应该初始化对象的方式,它是处于可用状态。

  • A constructor should initialize an object in a way that it's in a usable state.

一个构造函数应该只初始化一个对象,不执行繁重的工作。

A constructor should only initialize an object, not perform heavy work.

一个构造函数不应直接或间接调用虚成员或外部代码。

A constructor should not directly or indirectly call virtual members or external code.

因此,在大多数情况下,不应该要求一个初始化方法。

So in most cases an Initialize method shouldn't be required.

在情况下,初始化涉及不是将对象转换为可用状态(例如,当繁重的工作需要更多的要执行或虚拟成员或外部需要被调用),然后是初始化方法是一个不错的主意。

In cases where initialization involves more than putting the object into a usable state (e.g., when heavy work needs to be performed or virtual members or external need to be called), then an Initialize method is a good idea.

这篇关于初始化()与构造()方法,在对象创建正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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