简体   繁体   English

访问修改后的闭包-为什么建议这样做?

[英]Access to Modified Closure - why is this a suggested fix?

So I have code like this: 所以我有这样的代码:

int totalRequestsToSend = 0;
i = 1;

foreach (file in files)
{
    try
    {
        // This can throw if adding request fails for some reason, e.g. file does not exist
        requests.AddRequest(
            new FileStoreRequest(file)
            {
                OnStoreConfirm = (file) =>
                {
                    progress.Report((i*100)/totalRequestsToSend)
                    Interlocked.Increment(ref i);
                }
            }
            );
        totalRequestsToSend += 1;
    }
    catch(Exception e) {
        // handle exception
    }
}

Resharper complains with "access to modified closure" about line where I use totalRequestsToSend inside the lambda. Resharper抱怨我在lambda中使用totalRequestsToSend的行“对修改后的闭包的访问”。

The logic works as expected and complaint could be ignored, however, one of Resharper's suggested fixes changes the int variable to an array of size 1 like so: 逻辑按预期工作,投诉可以忽略,但是,Resharper建议的修复方法之一将int变量更改为大小为1的数组,如下所示:

int[] totalRequestsToSend = {0};
i = 1;

foreach (file in files)
{
    try
    {
        requests.AddRequest(
            new FileStoreRequest(file)
            {
                OnStoreConfirm = (file) =>
                {
                    progress.Report((i*100)/totalRequestsToSend[0])
                    Interlocked.Increment(ref i);
                }
            }
            );
        totalRequestsToSend[0] += 1;
    }
    catch(Exception e) {
        // handle exception
    }
}

This does not cause complaints from Resharper. 这不会引起Resharper的投诉。 I am puzzled. 我很困惑。 How is using an array different from using a variable in this case? 在这种情况下,使用数组与使用变量有何不同?

Thanks. 谢谢。

It's not any different. 没什么不同 The refactor accomplishes nothing productive. 重构无法完成任何工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM