在構造函數或聲明中初始化類字段? - Initialize class fields in constructor or at declaration?

問題:

I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.我最近一直在用 C# 和 Java 編程,我很好奇初始化我的類字段的最佳位置。

Should I do it at declaration?:我應該在聲明時這樣做嗎?:

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

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

or in a constructor?:還是在構造函數中?:

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.我想保持一致並堅持一種方法。


解決方案:

參考一: https://en.stackoom.com/question/6Nz
參考二: https://stackoom.com/question/6Nz
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章