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

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

问题描述

我在 VB.NET 中使用 LINQ,有时我会遇到类似

的查询

对于 i = 0 到 10Dim num = (From n In numbers Where n Mod i = 0 Select n).First()下一个

然后出现警告在 lambda 表达式中使用迭代变量可能会产生意想不到的结果.相反,在循环中创建一个局部变量并为其分配迭代变量的值."

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

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

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

解决方案

在这种立即计算 lambda 的特殊情况下,您可以通过将迭代变量的声明移出 for 循环来安全地消除警告.

p>

Dim i = 0对于 i = 0 到 10...

我确实想强调的是,这仅在 lambda 不逃脱 for 循环时才有效(对于您的场景是正确的).

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

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

and then it comes the warning "Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable."

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)

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.)

解决方案

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 
 ...

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 ...)

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

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