我该如何解决:在关闭resharper警告中访问foreach变量?

Est*_*ban 26 c# resharper

我收到了这个ReSharper警告:在关闭时访问foreach变量.使用不同版本的编译器编译时可能会有不同的行为.

这就是我正在做的事情:

@foreach(var item in Model)
{
    // Warning underlines "item".
    <div>@Html.DisplayBooleanFor(modelItem => item.BooleanField)</div>
}
Run Code Online (Sandbox Code Playgroud)

我的扩展如下:

public static MvcHtmlString DisplayBooleanFor<TModel, TValue>(
    this HtmlHelper<TModel> helper, 
    Expression<Func<TModel, TValue>> expression)
{
    bool value;

    try
    {
        var compiled = expression.Compile()(helper.ViewData.Model);
        value = Convert.ToBoolean(compiled);
    }
    catch (Exception)
    {
        value = false;
    }

    return MvcHtmlString.Create(value ? "Yes" : "No");
}
Run Code Online (Sandbox Code Playgroud)

请注意这是按预期工作但我如何避免此警告?
我将不胜感激任何帮助.

Cha*_*ion 25

块范围变量应解决警告.

@foreach(var item in Model)
{
    var myItem = item;
    <div>@Html.DisplayBooleanFor(modelItem => myItem.BooleanField)</div>
}
Run Code Online (Sandbox Code Playgroud)

  • @Esteban还有更多关于JetBrains维基[这里](http://confluence.jetbrains.net/display/ReSharper/Access+to+modified+closure)(这取决于您的R#版本可能直接链接到灯泡菜单为'为什么ReSharper暗示这个?); 另见[这个问题](http://stackoverflow.com/questions/235455/access-to-modified-closure?rq=1) (10认同)
  • @Esteban这是迄今为止我发现的最好的解释:http://stackoverflow.com/questions/14907987/access-to-foreach-variable-in-closure (2认同)