在构造函数或在声明初始化类字段? [英] Initialize class fields in constructor or at declaration?

查看:101
本文介绍了在构造函数或在声明初始化类字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#和Java编程了最近,我很好奇,什么是初始化你的类领域最好的地方?

I've been programming in C# and Java recently and I am curious what is the best place to initialize your classes fields?

如果您在声明中做到这一点:

Should you do it at declaration?:

public class Dice
{
    private int topFace = 1;
    private Random myRand = new Random();

    public void Roll()
    {
       // ......
    }
}

或在构造函数中。

public class Dice
{
    private int topFace;
    private Random myRand;

    public Dice()
    {
        topFace = 1;
        myRand = new Random();
    }

    public void Roll()
    {
        // .....
    }
}

我真的很好奇,你的一些老兵认为是最好的做法。我想保持一致,坚持一种方法。

I'm really curious what some of you veterans think is the best practice.. I want to be consistent and stick to one approach.

推荐答案

我的规则:


  1. 请不要在声明(默认值初始化0 0.0 ...)。

  2. 在声明preFER初始化,如果你没有改变的字段的值构造函数的参数。

  3. 如果因为构造函数的参数方面的变化值,把初始化的构造。

  4. 在你的做法(最重要的规则)是一致的。

  1. Don't initialize with the default values in declaration (null, false, 0, 0.0…).
  2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
  3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
  4. Be consistent in your practice (the most important rule).

这篇关于在构造函数或在声明初始化类字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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