为什么我的代码不计算天数的年龄?

时间:2017-03-14 11:51:13

标签: c#

我的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;   
}

当我执行它时,程序根本没有显示进度。它可能会挂起或陷入无限循环。是否由于程序必须进行大量处理?为什么我没有得到任何输出?

如果上述仅以天计算年龄的方法存在缺陷,那么更好/更简单的方法是什么?

1 个答案:

答案 0 :(得分:3)

DateTime是一个不可变的结构。您必须将DateTime.AddDays返回的内容分配给变量:

tempDay = tempDay.AddDays(1);

您可以使用TimeSpan.Days

以更简单,更有效的方式获得结果
int age = (DateTime.Today - birthDay).Days;