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 抱歉,我更改了代码,我的问题是,可以在循环中定义变量吗?

当然,在循环中定义变量是可以的。请注意,每次循环到达末尾“}”时,此变量的内容都会丢失。所以你最初的问题在这里无法回答,因为没有更好的表达方式。这取决于您的要求

于 2012-11-08T06:09:59.587 回答