关于构造函数 [英] About constructors

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

问题描述

我有一个关于构造函数的问题。我认为构造函数都只是我们的方便,而不是setter方法,对吧?因此,对于一个对象,你认为重要的属性(例如webform中的必填字段)作为参数传递给构造函数。

I got a question about Constructors.I think constructors are all just our convenience instead of setter methods,right? So for an object , the properties you think important(such as required fields in a webform)are passed as parameters into constructor.

有这些许多参数应该传递给构造函数?
请详细说明这些要点以及关于构造函数的任何要点。

Is there any criteria that these many number of parameters should be passed into constructor? Please elaborate on these points and as well as any points about constructors.

编辑:抱歉我的问题。是的,我们使用构造函数创建一个对象,并使用setter赋值,但我的问题是关于默认构造函数与setters和构造函数与显式参数之间的比较。

Edit:Sorry about the way i asked question.Yes,we create an object with constructor and we assign values with setters but my question is about the comparison between default constructor with setters and constructor with explicit parametrs.

推荐答案

不,这不只是方便而不是setters。特别是,构造函数只会被调用一次。使用构造函数参数,你可以创建不可变类型,在构建时给出它们的值 - 这对于setter是不可能的。

No, it's not just a convenience instead of setters. In particular, a constructor will only be called once. Using constructor parameters, you can create immutable types which are given their values at construction time - that wouldn't be possible with setters.

通常不是一个好主意巨大参数数量,无论是构造函数还是正常方法。如果您发现自己有很多参数,可以 创建一个表示所有相关类型的类型 - 类型可能有一堆getter / setter。请参见 ProcessStartInfo

It's generally not a great idea to have huge numbers of parameters, whether to a constructor or a normal method. If you find you have a lot of parameters, you may want to create a type representing all the related ones - that type may have a bunch of getters/setters. See ProcessStartInfo for an example of this.

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

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