我的C#代码是:
private int ageInDays()
{
string[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
int age = 0;
DateTime birthDay = new DateTime(Convert.ToInt32(yearCombo.Text), Array.IndexOf(month, monthCombo.Text) + 1, Convert.ToInt32(dayCombo.Text));
MessageBox.Show(birthDay.Date.ToString());
DateTime tempDay = birthDay;
DateTime today = DateTime.Today;
while (tempDay != today)
{
age++;
tempDay.AddDays(1);
}
return age;
}
当我执行它时,程序根本没有显示进度。它可能会挂起或陷入无限循环。是否由于程序必须进行大量处理?为什么我没有得到任何输出?
如果上述仅以天计算年龄的方法存在缺陷,那么更好/更简单的方法是什么?
答案 0 :(得分:3)
DateTime
是一个不可变的结构。您必须将DateTime.AddDays
返回的内容分配给变量:
tempDay = tempDay.AddDays(1);
您可以使用TimeSpan.Days
:
int age = (DateTime.Today - birthDay).Days;