简体   繁体   中英

Why does Resharper flag this as “access to modified closure”?

I'm sorry if this is a repeat question. I see many questions here about "modified closure", but none seem to address what I'm seeing.

Resharper 2016.2 is flagging both my use of "b" and "i1" inside the lambda expression as "access to modified closure". I don't think it should. I never use either b or i or i1 anywhere else in the program. Both are declared within the loop -- in fact, i1 was created by Resharper to resolve the modified closure issue with i. I can try to resolve it with i1 and it will just create an "int i2 = i1" and still give me the warning on i2! Surely this is not right. What am I missing here?

for (int i = 0; i < 10; ++i) {
    Button b = new Button();
    int i1 = i;
    Invoker.SyncInvoke(b, () => { b.Text = "number " + i1; });
}

EDIT: This has to be a bug. At one point in a certain source file (at line 424, to be precise) are these three lines:

        var collapsed = daSheet;
        int numrows = collapsed.GetLastNonEmptyRow(NonEmptyItemFlag.Data);
        int numcols = collapsed.GetLastNonEmptyColumn(NonEmptyItemFlag.Data);

If I paste the above snippet (the for loop above) BEFORE those lines, I get no warning. If I paste it AFTER those lines, I get a warning about both "b" and "i1". If I paste it between the 2nd and 3rd lines, I get the warning about "i1", but not b. That makes no sense.

" the false positive rate for some of their analyzers is pretty terrible" - your're right^^

In fact Resharper is not that wrong.

Imagine instead of Invoker... you would use sth like this Task.Startnew(...) I would assume(with only reading the source) that after executing you don't have 10 different buttons, you have only one and this one has the text "number 9".

Because the compiler brings the button and the i1 parameter within the lambda expression close together, it's worth it in general to have a look into the decompiled source code with dotpeek ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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