【发布时间】:2009-10-27 17:35:40
【问题描述】:
在 foreach 语句之外声明变量以及每次在其内部重新分配它(foreach)或在 foreach 中创建一个新变量对性能更好 例如
private List<ListItem> GetItems()
{
var items = new List<ListItem>();
var collection = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ListItem item;
foreach (var i in collection)
{
item = new ListItem { Text = i.ToString() };
items.Add(item);
}
return items;
}
还是这个?
private List<ListItem> GetItems()
{
var items = new List<ListItem>();
var collection = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (var i in collection)
{
ListItem item = new ListItem { Text = i.ToString() };
items.Add(item);
}
return items;
}
当然我在这里谈论项目对象。 谢谢大家。
【问题讨论】:
标签: c# scope variable-assignment