Ahm*_*gdy 6 c# scope variable-assignment
对于性能明智而言更好的是在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;
}
Run Code Online (Sandbox Code Playgroud)
还是这个?
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;
}
Run Code Online (Sandbox Code Playgroud)
肯定在这里我说的是物品对象.谢谢你们.
还有就是在那里这重要的一个边缘情况; 如果你将变量"捕获"到一个匿名方法/ lambda中.否则它是不成熟的,没有任何区别.完全没有.
它何时起作用的一个例子:
// prints all items in no particular order
foreach (var i in collection)
{
string s = i.ToString();
ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(s); });
}
Run Code Online (Sandbox Code Playgroud)
VS
// may print the same item each time, or any combination of items; very bad
string s;
foreach (var i in collection)
{
s = i.ToString();
ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(s); });
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1562 次 |
最近记录: |