gpt4 book ai didi

c# - Linq后期绑定(bind)困惑

转载 作者:行者123 更新时间:2023-11-30 13:33:14 26 4
gpt4 key购买 nike

有人可以解释一下我在这里缺少什么吗?根据我的基本理解,将在使用结果时计算 linq 结果,我可以在下面的代码中看到这一点。

 static void Main(string[] args)
{
Action<IEnumerable<int>> print = (x) =>
{
foreach (int i in x)
{
Console.WriteLine(i);
}
};

int[] arr = { 1, 2, 3, 4, 5 };
int cutoff = 1;
IEnumerable<int> result = arr.Where(x => x < cutoff);
Console.WriteLine("First Print");
cutoff = 3;
print(result);
Console.WriteLine("Second Print");
cutoff = 4;
print(result);
Console.Read();
}

输出:

First Print12Second Print123

Now I changed the

arr.Where(x => x < cutoff); 

IEnumerable<int> result = arr.Take(cutoff); 

输出如下。

First Print1Second Print1

为什么 Take 不使用变量的当前值?

最佳答案

您看到的行为来自评估 LINQ 函数的参数的不同方式。 Where 方法接收一个 lambda,它通过引用捕获值 cutoff。它是按需评估的,因此会看到当时 cutoff 的值。

Take 方法(以及类似的方法,如 Skip)接受一个 int 参数,因此 cutoff 被传递按值(value)。使用的值是调用 Take 方法时 cutoff 的值,而不是计算查询时的值

注意:此处的后期绑定(bind)一词有点不正确。后期绑定(bind)通常是指表达式绑定(bind)到的成员在运行时与编译时确定的过程。在 C# 中,您可以使用 dynamic 或反射来完成此操作。 LINQ 按需评估其部分的行为称为延迟执行。

关于c# - Linq后期绑定(bind)困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8930024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com