如何抑制VB的“迭代变量不应该在lambda表达式中使用” [英] How to suppress VB's "Iteration variable shouldn't been used in lambda expression"

查看:186
本文介绍了如何抑制VB的“迭代变量不应该在lambda表达式中使用”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用VB.NET中的LINQ,有时我会进行查询,如

I'm working with LINQ in VB.NET and sometimes I get to a query like

For i = 0 To 10
  Dim num = (From n In numbers Where n Mod i = 0 Select n).First()
Next

然后它出现警告在lambda表达式中使用迭代变量可能会产生意外结果。相反,在循环中创建一个局部变量并为其赋值迭代的值变量。

我知道在lambda表达式中使用迭代变量不是一个好习惯,因为只在需要时才计算lambda表达式。 (这个问题是关于那个)

I know it's not a good practice to use the iteration variable in the lambda expression, because lambda expressions are evaluated only when needed. (This question is about that)

现在我的问题是,如果在就地计算表达式的情况下如何抑制此警告,使用First(),Single等结构( ),ToList()等(这只是一个警告,但我喜欢我的代码干净。)

Now my question is, how to suppress this warning in cases where the expression is evaluated in-place, with constructions like First(), Single(), ToList(), etc. (It's only a warning, but i like my code clean.)

(声明一个局部变量并将迭代变量传递给它是一个选项,但我正在寻找一个干净的解决方案。)

(Declaring a local variable and passing the iteration variable to it is an option, but I'm looking for a clean solution.)

推荐答案

在这个特殊情况下,立即评估lambda,然后你可以通过在for循环外移动迭代变量的声明来安全地消除警告。

In this particular case where the lambda is evaluated immediately, then you can safely eliminate the warning by moving the declaration of the iteration variable outside the for loop.

Dim i = 0
For i = 0 To 10 
 ...

我确实想要强调这只有在lambda没有转义for循环时才有效(对于你的场景是真的)。

I do want to stress though that this only works if the lambda does not escape the for loop (true for your scenario).

这里还有一篇关于我在这个警告上写的文章的详细链接(为什么它存在,如何避免它等等)

Also here is a detailed link to an article I wrote on this warning (why it exists, how to avoid it, etc ...)

  • http://blogs.msdn.com/b/jaredpar/archive/2007/07/26/closures-in-vb-part-5-looping.aspx

这篇关于如何抑制VB的“迭代变量不应该在lambda表达式中使用”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆