简体   繁体   中英

Why does Resharper suggest a code change and then complain about the change?

I had this code:

return children.SelectMany(c => GetChildControls<TControl>(c)).Concat(children);

...and Resharper suggested I change it to this:

return children.SelectMany(GetChildControls<TControl>).Concat(children);

In context:

internal static IEnumerable<TControl> GetChildControls<TControl>(this Control control) where TControl : Control
{
    var children = control.Controls != null ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>();
    return children.SelectMany(GetChildControls<TControl>).Concat(children);
}

The difference, as you probably saw, is that the "improved" version of the line has ommitted the inserted "(c)"

But now it flags that as suspicious, saying, "Possible multiple enumeration of IEnumerable"

Yeah, that's right, there could/should be multiple, but why is it whin[g]ing about that? Should I revert it to its previous state?

The problem that ReSharper is picking up for you is that you are enumerating children twice. Specifically, you enumerate children the first time when you call children.SelectMany(GetChildControls<TControl>) and another time when you call .Concat(children) on that. ReSharper warns you about this because each enumeration could result in different results, or each enumeration could be costly. See this question for more details.

One solution would be

internal static IEnumerable<TControl> GetChildControls<TControl>(this Control control) where TControl : Control
{
    var children = control.Controls.OfType<TControl>().ToList();
    return children.SelectMany(GetChildControls<TControl>).Concat(children);
}

which makes sure children will not vary inside your method after you create it (unless, of course, you mutate it yourself) and that it will only be enumerated once.

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