开发者

Warning: "Using the iteration variable in a lambda expression may have unexpected results"

Edit: Here is a much more simpler example of this issue (i've deleted my original question):

Dim numbers1 As New List(Of Int32)({1, 2, 3})
Dim numbers2 As New List(Of Int32)({3, 4, 5})
For Each n1 In numbers1
    ' no wa开发者_StackOverflowrning '
    Dim contains = numbers2.Contains(n1)
Next
For Each n1 In numbers1
    ' warning on n1'
    Dim contains = (From num In numbers2 Where num = n1).Any
Next

So i still don't understand why the compiler thinks that i may get unexpected results in the second iteration whereas i'm safe with the first. I don't think that the interesting link of @ee-m provides the reason for this behaviour,(this is not a for-each issue, For n1 As Int32 = 1 To 3 would also result in a compiler warning).

I'm not really convinced that following should be "best-practice":

For Each n1 In numbers1
    Dim number1 = n1
    ' no warning'
    Dim contains = (From num In numbers2 Where num = number1).Any
Next

The local variable number1 is redundant and makes the code less readable as @Meta-Knight already has emphasized. Note: All three ways are safe and give the correct result.


Eric Lippert wrote a couple of blog posts on this topic (code examples are in C#, not VB) which goes over some of the "gotchas" that can arise from this sort of code which you may find interesting:

Closing over the loop variable considered harmful


As the message says, it "may have" undesired effects. In your case the .ToList() makes it safe but that is hard for the compiler to verify.

I would suggest to adopt copying to a local var (Dim exc = excel) as standard 'best practice'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜