我讀的書曼寧有關LINQ,有一個例子:LINQ表達式中的值是否通過引用傳遞?
static class QueryReuse
{
static double Square(double n)
{
Console.WriteLine("Computing Square("+n+")...");
return Math.Pow(n, 2);
}
public static void Main()
{
int[] numbers = {1, 2, 3};
var query =
from n in numbers
select Square(n);
foreach (var n in query)
Console.WriteLine(n);
for (int i = 0; i < numbers.Length; i++)
numbers[i] = numbers[i]+10;
Console.WriteLine("- Collection updated -");
foreach (var n in query)
Console.WriteLine(n);
}
}
與下面的輸出:
Computing Square(1)...
1
Computing Square(2)...
4
Computing Square(3)...
9
- Collection updated -
Computing Square(11)...
121
Computing Square(12)...
144
Computing Square(13)...
169
這是否意味着,「數字」是按引用傳遞?這種行爲是否需要執行懶惰的執行和收益?或者我在這裏錯了嗎?
「按引用傳遞」和「按值傳遞引用」有所不同。請參閱http://pobox.com/~skeet/csharp/parameters.html – 2010-09-22 09:16:47