class Program
{
static void Main(string[] args)
{
foreach(int i in getList())
{
Console.WriteLine("Current index is " + i.ToString());
}
Console.ReadLine();
}
private static List<int> getList()
{
Console.WriteLine("get list");
List<int> l = new List<int>();
l.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
return l;
}
}
输出结果:
get list
Current index is 1
Current index is 2
Current index is 3
Current index is 4
Current index is 5
Current index is 6
Current index is 7
Current index is 8
Current index is 9
Current index is 10
可见,Foreach 和 For 相比,性能提升了。