C#哪个表达正确或更好?

时间:2012-11-08 05:25:52

标签: c#

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");
}

这是正确还是更好的表达?还是一样?

2 个答案:

答案 0 :(得分: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,或者您需要在迭代之间保持其值。

答案 1 :(得分:0)

  

@recursive抱歉,我改变了代码,我的问题是,在循环中定义变量是否可以?

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

相关问题