为什么要在构造函数中初始化成员变量? [英] Why should member variables be initialized in constructors?

查看:482
本文介绍了为什么要在构造函数中初始化成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我第一次开始使用面向对象的编程语言时,我被教导以下规则:

When I first started working with object-oriented programming languages, I was taught the following rule:

在类中声明字段时,请不要初始化它.在构造函数中执行该操作.

When declaring a field in a class, don't initialize it yet. Do that in the constructor.

C#中的示例:

public class Test
{
    private List<String> l;

    public Test()
    {
        l = new List<String>();
    }
}

但是当最近有人问我为什么这样做时,我无法提出一个原因. 我对C#(或其他编程语言)的内部运作并不十分熟悉,因为我相信这可以在所有OO语言中完成.

But when someone recently asked me why to do that, I couldn't come up with a reason. I'm not really familiar with the internal workings of C# (or other programming languages, for that matter, as I believe this can be done in all OO languages).

那为什么 完成了?安全吗?属性?

So why is this done? Is it security? Properties?

推荐答案

  • 如果您有多个构造函数,则可能需要将字段初始化为不同的值

    • If you have multiple constructors, you might want to initialize a field to different values

      在构造函数中初始化字段时,对于其余构造函数而言,何时完全初始化该字段不会引起混淆.对于单个类来说,这似乎是微不足道的,但是当您具有一个继承层次结构,并且构造函数代码在每个级别上运行并访问超类字段时,则显得不那么重要了.

      When you initialize the field in the constructor, there can be no confusion over when exactly it is initialized in regard to the rest of the constructor. This may seem trivial with a single class, but not so much when you have an inheritance hierarchy with constructor code running at each level and accessing superclass fields.

      这篇关于为什么要在构造函数中初始化成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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