我最近一直在用c#和Java编程,我很好奇初始化我的类字段的最佳位置在哪里。
我应该在申报时申报吗?:
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()
{
// .....
}
}
我很好奇你们这些老兵认为最好的做法是什么。我想保持一致,坚持一种方法。
In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has in all cases, regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same.
有许多不同的情况。
我只需要一个空列表
情况很清楚。我只需要准备我的列表,并防止在有人向列表添加项时抛出异常。
public class CsvFile
{
private List<CsvRow> lines = new List<CsvRow>();
public CsvFile()
{
}
}
我知道价值观
我确切地知道在默认情况下我想要什么值,或者我需要使用一些其他逻辑。
public class AdminTeam
{
private List<string> usernames;
public AdminTeam()
{
usernames = new List<string>() {"usernameA", "usernameB"};
}
}
or
public class AdminTeam
{
private List<string> usernames;
public AdminTeam()
{
usernames = GetDefaultUsers(2);
}
}
可能值的空列表
有时我希望默认情况下是一个空列表,并可以通过另一个构造函数添加值。
public class AdminTeam
{
private List<string> usernames = new List<string>();
public AdminTeam()
{
}
public AdminTeam(List<string> admins)
{
admins.ForEach(x => usernames.Add(x));
}
}