vb.net 中的 List.ForEach - 让我困惑
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8897906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List.ForEach in vb.net - perplexing me
提问by Graham Whitehouse
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.
我希望结果是相同的,但是第二个代码示例不会更改列表 TempList 中的对象。
This post is more to understand why...? Or at least get some help understanding why...
这篇文章更能理解为什么...?或者至少得到一些帮助来理解为什么......
回答by Meta-Knight
It's because you used Function
instead of Sub
. Since a Function
returns a value, the compiler considers that the equals sign (=) is used as a comparison, not an assignment. If you change Function
to Sub
, the compiler would correctly consider the equals sign as an assignment:
这是因为你使用了Function
而不是Sub
. 由于 aFunction
返回一个值,编译器认为等号 (=) 用作比较,而不是赋值。如果更改Function
为Sub
,编译器会正确地将等号视为赋值:
TempList.ForEach(Sub(obj) obj.Deleted = True)
If you had a multiline lambda; you wouldn't have had this problem:
如果您有一个多行 lambda;你不会有这个问题:
TempList.ForEach(Function(obj)
obj.Deleted = True
Return True
End Function)
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 a Sub
.
显然,对于 ForEach 方法,使用 a 没有意义,Function
因为不会使用返回值,因此您应该使用 a Sub
。