while 无限循环

Infinite Loop during while

为什么这是 运行 无限期而不增加天数

var startDate = new DateTime(year, 1, 1);
var endDate = startDate.AddYears(1);

while (startDate < endDate)
{
    startDate.AddDays(1);
}

目标是循环遍历一年中的所有日子。

谢谢!

在 .NET 中 DateTime 是不可变的,因此 AddDays 方法只是 returns 新日期,不会更改 startDate 本身。

您应该将此新值重新分配给 startDate

startDate = startDate.AddDays(1);

startDate.AddDays(1); 不会改变 startDate,因此 startDate < endDate 始终为真。

为了避免此类 讨厌的错误(不分配回 AddDays(1) 结果)我建议实施 for 循环而不是 while

  for (var date = new DateTime(year, 1, 1); 
           date < new DateTime(year + 1, 1, 1); 
           date = date.AddDays(1)) {
    ...
  }