我在代码中定义了这些变量,我想一步对其进行初始化,该怎么办?
class FemaleClub(name: String, country: String): Club(name = name, country = country)
例如:
int currentYearSavingDays, currentYearSavingXMins, currentYearSavingNXMins, currentYearUsedDays, currentYearUsedXMins, yearLimitRemainingDays, yearLimitRemainingXMins, totalYearlyDays, totalYearlyXMins, totalSavingDays, totalSavingMins, totalUsableDays, totalUsableMins, nextYearTotalUsableDays, nextYearTotalUsableMins, dayWorkMinutes, previousYearRemainingDays, previousYearRemainingMins;
答案 0 :(得分:5)
我不愿一次全部声明它们。除了丑陋的阅读之外,没有必要。
相反,这似乎是class或struct的一组字段的理想选择。
在C#中,value type个字段被分配,并由memory manager自动初始化为其默认值。因此,在这种特殊情况下,如果仅为这些值创建了新的类/结构,则无需显式初始化它们。
请注意,只要您小心不要违反single responsibility principle,就可以将它们也保留为当前类中的字段。
还要注意,如果答案为local variables,则此答案中描述的策略将不起作用。正如this answer所解释的,尽管初始化语义相同,但是未初始化的局部变量的使用通常是一个错误,在C#中是不允许的。在这种情况下,我认为最好在自己的行上声明和初始化每个变量。
答案 1 :(得分:4)
我所知道的就是这个。
int currentYearSavingDays, currentYearSavingXMins, currentYearSavingNXMins, currentYearUsedDays, currentYearUsedXMins, yearLimitRemainingDays, yearLimitRemainingXMins, totalYearlyDays, totalYearlyXMins, totalSavingDays, totalSavingMins, totalUsableDays, totalUsableMins, nextYearTotalUsableDays, nextYearTotalUsableMins, dayWorkMinutes, previousYearRemainingDays, previousYearRemainingMins;
currentYearSavingDays = currentYearSavingXMins = currentYearSavingNXMins = currentYearUsedDays = currentYearUsedXMins = yearLimitRemainingDays = yearLimitRemainingXMins = totalYearlyDays = totalYearlyXMins = totalSavingDays = totalSavingMins = totalUsableDays = totalUsableMins = nextYearTotalUsableDays = nextYearTotalUsableMins = dayWorkMinutes = previousYearRemainingDays = previousYearRemainingMins = 0;
答案 2 :(得分:0)
您可以这样声明和初始化:
int iOne = 1, iTwo = 2, iThree = 3;
变量初始化是可选的
此行
int iOne,iTwo,iThree;
将所有变量都设置为零。