For-each 循环变量
下面的代码中 ob 意味着什么 - 这与 item 相同吗?
foreach (var item in allItems)
{
if (excludeItems.Exists(ob => ob.Equals(item)))
{
Console.WriteLine("Item {0} excluded",item);
}
}
What does ob means in following code - is this same as item?
foreach (var item in allItems)
{
if (excludeItems.Exists(ob => ob.Equals(item)))
{
Console.WriteLine("Item {0} excluded",item);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ob
是 lambda 表达式 的参数。因此,如果您熟悉匿名方法,就像:假设
ob
的类型应该是string
- 它很可能不是。由于泛型类型推断,这将取决于excludeItems
。Lambda 表达式可以更明确,因此可以写为:
或者
基本上,对于可以推断类型的单个参数的常见情况,Lambda 表达式中有一些小快捷方式,并且返回值一个单一的表达。
现在,在这种特殊情况下,将从 lambda 表达式创建的委托将为
excludeItems
中的每个元素(在foreach
循环的每次迭代中)和ob 调用一次。
将具有该元素的值,直到找到等于item
的值(或用完所有元素)。ob
is the parameter to the lambda expression. So if you're familiar with anonymous methods, it's like:That's assuming the type of
ob
should bestring
- it may well not be. That will depend ofexcludeItems
, due to generic type inference.Lambda expressions can be more explicit, so this could be written as:
or
Basically there are several little shortcuts in lambda expressions for the common case of a single parameter whose type can be inferred, and a return value from a single expression.
Now in this particular case, the delegate created from the lambda expression will be called once for each element in
excludeItems
(in each iteration of theforeach
loop) andob
will have the value of that element, until it finds a value equal toitem
(or runs out of elements).ob 表示 exceptItems 中的项目
ob means an item in excludeItems