C#中使用DateTime计算年龄时BirthDate被重置为01-01-0001求助
问题分析与解决方案
首先,我们来定位你遇到的核心问题:
- 你实际上创建了两个
Customer实例:- 第一个是
Customer cust = new Customer();——这个实例用无参构造函数初始化,没有给BirthDate赋值,所以它的BirthDate会是DateTime类型的默认值01-01-0001。 - 第二个是
new Customer("Lionel Messi", new DateTime(2000, 3, 12), new DateTime(2019, 2, 23))——这个实例通过带参构造函数赋值,BirthDate应该是你设置的2000-03-12。
- 第一个是
你在调试时大概率查看的是第一个实例(cust)的BirthDate,而不是传入VoegToe方法的第二个实例的属性,所以才会看到默认值。
验证方法
调试时不要盯着cust对象的BirthDate,而是查看VoegToe方法内部接收到的Customer参数,或者查看cust.customers列表里的第一个元素——这个元素的BirthDate肯定是你设置的2000-03-12。
额外优化建议
为了避免类似混淆和潜在问题,建议做以下调整:
- 构造函数的参数名用小写开头(比如
birthDate),和属性名区分开,提升代码可读性:public Customer(string name, DateTime birthDate, DateTime signUpDate) { this.name = name; this.signUpDate = signUpDate; this.BirthDate = birthDate; } - 如果你不需要无参构造函数,可以直接移除它;如果需要,建议在无参构造里显式初始化
BirthDate,避免出现默认值混淆。 - 你的
Age计算方式有小缺陷:用总天数除以365没考虑闰年的情况,更准确的计算方式可以参考:public int Age { get { var today = DateTime.Today; int age = today.Year - BirthDate.Year; // 如果今年还没到生日,年龄减1 if (BirthDate.Date > today.AddYears(-age)) age--; return age; } }
内容的提问来源于stack exchange,提问作者Jordy Pouw
相关产品推荐
相关产品推荐

