0
DateTime theMonth = DateTime.Now;
for(int i = 0; i<8; i++){
     string curMonth = theMonth.AddMonths(-i).ToString("MM/yyyy");
}

または、

DateTime theMonth = DateTime.Now;
string curMonth;
for(int i = 0; i<8; i++){
     curMonth = theMonth.AddMonths(-i).ToString("MM/yyyy");
}

どちらが正しいか、より良い表現ですか? それとも同じ?

4

2 に答える 2

4

使用する

DateTime theMonth = DateTime.Now;
for(int i = 0; i<8; i++){
     string curMonth = theMonth.AddMonths(-i).ToString("MM/yyyy");
}

ループ内でのみ使用する予定でcurMonthあり、その値をループの反復間で保持する必要がない場合。

使用する

DateTime theMonth = DateTime.Now;
string curMonth;
for(int i = 0; i<8; i++){
     curMonth = theMonth.AddMonths(-i).ToString("MM/yyyy");
}

ループコードの実行が終了した後に使用する予定がある場合curMonth、または反復間で値を保持するために値が必要な場合。

于 2012-11-08T06:12:49.187 に答える
0

@recursive sorry I changed code, my question is, is it OK to define variable in loop?

Of course it is ok to define variables in a loop. Just notice that the content of this variable will be lost everytime the loop reaches the end "}". So your initial question can't be answered here because there is no better expression. It depends on your requirements

于 2012-11-08T06:09:59.587 に答える