3

我在选定索引上更改了代表月份的下拉列表的此代码。

    DateTime firstDate, lastDate;
    int mon = DropDownList1.SelectedIndex +1;
    int year = 2013;

    GetDates(mon, year,out firstDate , out lastDate);
    DateTime f = firstDate;
    DateTime d2 = firstDate.AddDays(7);
    for (;d2.Month  == mon;  )
    {
        d2.AddDays(7);   // value after first iteration is "08-Apr-13 12:00:00 AM"
                        // but beyond first iteration the value remains the same.
    }


    private void GetDates(int mon, int year, out DateTime firstDate, out DateTime lastDate)
    {       
        int noOfdays = DateTime.DaysInMonth(year, mon);
        firstDate = new DateTime(year, mon, 1);
        lastDate = new DateTime(year, mon, noOfdays);
    } 

我希望 d2 将在每次迭代中继续增加 7 天,只要结果值在同一个月内。但似乎价值只增加一次。即从 01-Apr-13 12:00:00 AM 到 08-Apr-13 12:00:00 AM

4

2 回答 2

13

您必须将更改的日期对象分配回日期对象d2,因为 DateTime 对象是不可变的。AddDays方法返回对象而不是更改调用它的对象,因此您必须将其分配回调用对象。

d2 = d2.AddDays(7);

编辑为什么它适用于第一次迭代?

因为您通过在循环前添加 7 天来初始化日期对象。

DateTime d2 = firstDate.AddDays(7);
于 2013-05-07T11:54:38.253 回答
5

不应该吗?

d2 = d2.AddDays(7);
于 2013-05-07T11:55:27.130 回答