C# 中 lambda 变量的范围是什么? [英] What is the scope of a lambda variable in C#?
问题描述
我对 lambda 变量的范围感到困惑,例如以下内容
I'm confused about the scope of the lambda variable, take for instance the following
var query =
from customer in clist
from order in olist
.Where(o => o.CustomerID == customer.CustomerID && o.OrderDate == // line 1
olist.Where(o1 => o1.CustomerID == customer.CustomerID) // line 2
.Max(o1 => o1.OrderDate) // line 3
)
select new {
customer.CustomerID,
customer.Name,
customer.Address,
order.Product,
order.OrderDate
};
在第 1 行中,我声明了一个 lambda 变量o",这意味着我无法在第 2 行中再次声明它(或者至少编译器会在我尝试时抱怨)但是即使 'o1' 已经存在,它也不会抱怨第 3 行??
In line 1 I have declare a lambda variable 'o' which means I cannot declare it again in line 2 (or at least the compiler complains if I try to) But it doesn't complain about line 3 even though 'o1' already exists??
lambda 变量的作用域是什么?
What is the scope of a lambda variable?
推荐答案
括号给出了线索 - lambda 变量在其声明的范围内被捕获:
The brackets give the clue - the lambda variable is captured in the scope of where it's declared:
.Where(o => ... olist.Where(o1 => ...).Max(o1 => ...))
// |----------------------------------------------| scope of o
// |---------| scope of first o1
// |---------| scope of second o1
请注意,两个 o1
变量没有重叠,但它们都重叠(或隐藏)了 o
变量,因此不能使用相同的名称.
Note that there's no overlap for the two o1
variables, but they both overlap (or shadow) the o
variable and hence can't use the same name.
这篇关于C# 中 lambda 变量的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!