为什么.Aggregate(...)中的后递增失败但是预递增成功?(Why does post

编程入门 行业动态 更新时间:2024-10-28 04:30:44
为什么.Aggregate(...)中的后递增失败但是预递增成功?(Why does post-increment fail in .Aggregate(…) but pre-increment succeeds?)

我正在摆弄我的一个项目欧拉答案,试着让它更短/更清洁/简洁。

我想出了这个:

Sequences.FibonacciBig() // infinite fib sequence of type BigInteger .TakeWhile(f => f.ToString().Length < 1000) .Aggregate(1, (i, _) => i++);

我的测试失败,因为实际是1,这似乎很奇怪。 我首先想到的是懒惰的可枚举没有被评估或类似的东西。 我替换为i + = 1并且它工作,测试通过。 然后我用++ i替换它仍然有效。

我很困惑为什么在使用后增量运算符时,该语句似乎根本没有被评估。 在最坏的情况下,我预计会出现某种类型的逐个错误,但不会使聚合函数无效地执行任何操作。

谁能解释一下?

I was fiddling with one of my project euler answers to try and make it a bit shorter/cleaner/succinct.

I came up with this:

Sequences.FibonacciBig() // infinite fib sequence of type BigInteger .TakeWhile(f => f.ToString().Length < 1000) .Aggregate(1, (i, _) => i++);

My test failed as the actual was 1, which seemed odd. I first thought that the lazy enumerable wasn't being evaluated or something like that. I replaced with i += 1 and it worked, test passed. Then I replaced with ++i and it still worked.

I'm confused as to why the statement seems to not be evaluated at all when using the post-increment operator. At worst, I expected some kind of off-by-one error, but not have the aggregate function effectively do nothing.

Can someone explain?

最满意答案

看下面的代码:

private int value = 0; public int GetValue() { return value++; }

当你第一次打电话时,你会期望它返回1吗? 它没有。 它返回值的当前值,然后递增它。 你的lambda表达式也是如此。

.Aggregate(1, (i, _) => i++);

它返回i当前值,然后递增它(在那一点没有意义,因为你没有在其他任何地方保持对它的引用)。

pre-increment和+= work,因为它们在返回之前递增值。

Look at following code:

private int value = 0; public int GetValue() { return value++; }

would you expect it to return 1 when called for the first time? It doesn't. It returns current value of value and than increments it. The same happens to your lambda expression.

.Aggregate(1, (i, _) => i++);

It returns current value of i, and than increments it (which is pointless at that point as you're not holding reference to it anywhere else).

pre-increment and += work because they increment the value before returning it.

更多推荐

本文发布于:2023-07-16 12:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128513.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Aggregate   post

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!