为什么reshaper会提示“将变量包装在数组中”?访问修改后的关闭警告? [英] Why does resharper suggest "wrap variable in array" for access to modified closure warnings?

查看:82
本文介绍了为什么reshaper会提示“将变量包装在数组中”?访问修改后的关闭警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下(经过大量编辑的伪)代码:

Given the following (heavily edited, pseudo-)code:

int count = 0;
thing.Stub(m => m.AddBlah()).WhenCalled(o => count++);
thing.Stub(m => m.RemoveBlah()).WhenCalled(o => count--);

DoStuff(thing);

Assert.AreEqual(1, count);

ReSharper提供计数警告-访问已修改的闭包。我理解为什么收到此警告(在两个不同的lambda中修改了count变量,并且可能具有不期望的语义),但我不理解ReSharper的建议:将局部变量包装在数组中。如果我让ReSharper这样做,我将得到:

ReSharper provides a warning on count - "Access to modified closure". I understand why I'm getting this warning (the count variable is being modified in two different lambdas, and is likely to have undesirable semantics), but I don't understand ReSharper's advice: "Wrap local variable in array". If I let ReSharper do this, I get:

int count[] = { 0 };
thing.Stub(m => m.AddBlah()).WhenCalled(o => count[0]++);
thing.Stub(m => m.RemoveBlah()).WhenCalled(o => count[0]--);

DoStuff(thing);

Assert.AreEqual(1, count[0]);

而且没有警告。

为什么使用数组保险柜?

Why is using an array safe?

推荐答案

我自己在ReSharper中注意到了同样的事情,并且还想知道为什么它没有警告当值包装在数组中时。不幸的是,这里的另一个答案是错误的,并且似乎误解了闭包是如何实现的,所以我想尝试解释一下(我认为是)重构背后的原理。

I noticed this same thing in ReSharper myself, and was also left wondering why it doesn't warn when the value is wrapped in an array. The other answer here is unfortunately wrong, and seems to misunderstand how closures are implemented, so thought I would attempt explain (what I think is) the rationale behind this refactoring.

如您所见,无论是否用数组包装,结果都是相同的,因此重构并不能真正解决任何问题,在应用更改后,访问普通的已修改闭包时可能遇到的相同问题。但是,由于自 count array 本身以来未进行更改(仅包含其内容),因此更改之后,不会显示访问已修改的闭包警告。

As you've seen, the result is the same whether array-wrapped or not, so the refactoring doesn't really "fix" anything and the same issues that can be encountered when accessing an ordinary modified closure exist after applying the change. However, after the change since the count array itself is not being modified (only its contents), the "Access to modified closure" warning is no longer relevant.

(至少在我看来),这种改变并没有使问题变得更加明显,因此,该建议似乎在告诉ReSharper忽略该问题,而不必求助于麻烦的 // ReSharper禁用AccessToModifiedClosure 机制来抑制该错误。

The change doesn't really make the problem any more obvious in (at least in my opinion), so it would seem that this suggestion is essentially telling ReSharper to ignore the issue, without having to resort to the rather messy // ReSharper disable AccessToModifiedClosure mechanism to suppress the error.

这篇关于为什么reshaper会提示“将变量包装在数组中”?访问修改后的关闭警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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