How do I fix: Access to foreach variable in closure resharper warning?

I'm getting this ReSharper warning: Access to foreach variable in closure. May have different behaviour when compiled with different versions of compiler .

This is what I'm doing:

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

My extension is as follows:

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");
}

Note this is working as expected but how can I avoid this warning?
I'll appreciate any help provided.


块范围变量应解决警告。

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

另一个选项是将JetBrains.Annotations.InstantHandleAttribute属性应用于DisplayBooleanFor方法。

链接地址: http://www.djcxy.com/p/52816.html

上一篇: LINQifying我的代码值得在闭包中访问一个foreach变量吗?

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