在构造函数或声明中初始化类字段? [英] Initialize class fields in constructor or at declaration?
本文介绍了在构造函数或声明中初始化类字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我最近一直在用 C# 和 Java 编程,我很好奇初始化类字段的最佳位置.
I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.
我应该在申报时做吗?:
Should I 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.
推荐答案
我的规则:
- 不要使用声明中的默认值进行初始化(
null
、false
、0
、0.0
...). - 如果您没有更改字段值的构造函数参数,则首选声明中的初始化.
- 如果字段的值因构造函数参数而改变,则将初始化放在构造函数中.
- 在您的实践中保持一致(最重要的规则).
这篇关于在构造函数或声明中初始化类字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文