无法在循环中多次添加日期

Sam*_*ack 3 c# asp.net c#-4.0

我在选定的索引上有这个代码更改了一个表示月份的下拉列表.

    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);
    } 
Run Code Online (Sandbox Code Playgroud)

我希望d2会在每次迭代中持续增加7天,只要结果值在同一个月内.但似乎价值只增加一次.即从01年4月1日至上午12:00:00至08日 - 4月13日12:00:00 AM

Adi*_*dil 13

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

d2 = d2.AddDays(7);
Run Code Online (Sandbox Code Playgroud)

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

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

DateTime d2 = firstDate.AddDays(7);
Run Code Online (Sandbox Code Playgroud)


小智 5

不应该吗?

d2 = d2.AddDays(7);
Run Code Online (Sandbox Code Playgroud)