目前我正在尝试计算具有给定生日的人的年龄,但每当我运行我的代码时,生日重构为默认的01-01-0001。
Birthdate设置在这里:
私人的 …
那么,你的逻辑是有缺陷的。最重要的是,因为它没有考虑到闰年。另一件事是,那个 DateTime class为您提供开箱即用的所有功能。
DateTime
为了使其可测试,显然,您还应该尝试将给定日期作为参数:
static class AgeCalculator { static int GetAgeInYears(DateTime birth) => GetAgeInYears(brith, DateTime.Today); static int GetAgeInYears(DateTime birth, DateTime mes) { var age = mes.Year - birth.Year - 1; // if the birthday already has past (or is today) if(birth.Month > mes.Month || (birth.Month == mes.Month && birth.Day => mes.Day) { age++; } return age; }
更先进的方法是创建一个 DateTimeSpan class / struct,它还跟踪年龄的天数(和月数)。但在大多数情况下,这不是用例的一部分。
DateTimeSpan
我刚刚测试了您提供的代码,它可以很好地与1位客户合作。您遇到的问题可能在于列表,并且客户类包含客户列表以及您如何访问实例化对象的时代。
这很好用:
public class Customer { private string name; private DateTime signUpDate; public DateTime BirthDate { get; } public int Age { get { int Age = (int)(DateTime.Today - BirthDate).TotalDays; Age = Age / 365; return Age; } } public Customer(string name, DateTime BirthDate, DateTime signUpDate) { this.name = name; this.signUpDate = signUpDate; this.BirthDate = BirthDate; } }
使用按钮计算年龄并显示:
private void button1_Click(object sender, EventArgs e) { Customer test = new Customer("Lionel Messi", new DateTime(2000, 3, 12), new DateTime(2019, 2, 23)); teAge.Text = test.Age.ToString(); }
如果你想准确发布你如何访问年龄,我可以帮助你更多。