vb.net 中的 List.ForEach - 让我困惑
考虑以下代码示例:
TempList.ForEach(Function(obj)
obj.Deleted = True
End Function)
而这个:
TempList.ForEach(Function(obj) obj.Deleted = True)
我希望结果是相同的,但是第二个代码示例不会更改列表 TempList 中的对象。
这篇文章更能理解为什么......?或者至少得到一些帮助来理解为什么......
Consider the following code example:
TempList.ForEach(Function(obj)
obj.Deleted = True
End Function)
And this one:
TempList.ForEach(Function(obj) obj.Deleted = True)
I would expect the results to be the same, however the second code example does NOT change the objects in the list TempList.
This post is more to understand why...? Or at least get some help understanding why...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为您使用了
Function
而不是Sub
。由于Function
返回一个值,因此编译器认为等号 (=) 用作比较,而不是赋值。如果将Function
更改为Sub
,编译器会正确地将等号视为赋值:如果您有一个多行 lambda;你不会遇到这个问题:
显然,对于 ForEach 方法,使用
Function
是没有意义的,因为不会使用返回值,所以你应该使用Sub< /代码>。
It's because you used
Function
instead ofSub
. Since aFunction
returns a value, the compiler considers that the equals sign (=) is used as a comparison, not an assignment. If you changeFunction
toSub
, the compiler would correctly consider the equals sign as an assignment:If you had a multiline lambda; you wouldn't have had this problem:
Obviously, for the ForEach method it makes no sense to use a
Function
because the return value wouldn't be used, so you should use aSub
.