什么是C#的lambda变量的范围有多大? [英] What is the scope of a lambda variable in C#?
问题描述
我困惑的拉姆达变量的范围,就拿以下
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(或至少编译器会抱怨,如果我尝试)
但这并不抱怨3号线,即使'01'已经存在??
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?
推荐答案
括号给出线索 - 拉姆达变量在哪里范围抓获它宣称:
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
注意有两个 01 没有重叠code>变量,但他们都重叠(或阴影)的
0
变量,因此不能使用相同的名称。
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屋!