LINQ表达式中的值是否通过引用传递? [英] Are values in LINQ expressions passed by reference?

查看:70
本文介绍了LINQ表达式中的值是否通过引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关LINQ的手册,并且有一个示例:

I'm reading manning book about LINQ, and there is an example:

    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

这是否意味着数字"是通过引用传递的?这种行为是否与懒惰的执行和屈服有关系?还是我在这里走错了路?

Does this means, that 'numbers' is passed by reference? Does this behavior have to do something with lazy execution and yield? Or I'm on a wrong track here?

推荐答案

这与延迟执行有关.每次您遍历查询时,都将再次查看numbers.确实,如果在执行查询的同时更改numbers 的Late元素的值,则也会看到该变化.这都改变了数组的 contents .

It's to do with lazy execution. Every time you iterate through the query, that will be looking at numbers again. Indeed, if you change the value of a late element of numbers while you're executing the query, you'll see that change too. This is all changing the contents of the array.

请注意,查询在创建查询时会记住numbers的值-但该值是引用,而不是数组的 contents .因此,如果您像这样更改numbers本身的值:

Note that the query remembers the value of numbers at the time of the query creation - but that value is a reference, not the contents of the array. So if you change the value of numbers itself like this:

numbers = new int[] { 10, 9, 8, 7 };

然后,更改不会反映在查询中.

then that change won't be reflected in the query.

如果您在查询的其他部分中使用变量,则只会使事情复杂化,例如:

Just to complicate things, if you use variables within other parts of the query, like this:

int x = 3;

var query = from n in numbers
            where n == x
            select Square(n);

然后捕获变量 x而不是其值...因此,更改x将更改评估查询的结果.这是因为查询表达式实际上已转换为:

then the variable x is captured rather than its value... so changing x will change the results of evaluating the query. That's because the query expression is really translated to:

var query = numbers.Where(n => n == x)
                   .Select(n => Square(n));

请注意,在这里,x用于lambda表达式中,但没有使用numbers-这就是它们的行为略有不同的原因.

Note that here, x is used within a lambda expression, but numbers isn't - that's why they behave slightly differently.

这篇关于LINQ表达式中的值是否通过引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆