如何抑制 VB 的“迭代变量不应在 lambda 表达式中使用”

发布于 2024-09-25 12:18:44 字数 589 浏览 3 评论 0原文

我在 VB.NET 中使用 LINQ,有时我会遇到类似这样的查询

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

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

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷途知返 2024-10-02 12:18:44

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

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

我确实想强调,这仅在 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 
 ...

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文