2012-09-22 46 views
25

我收到了这个ReSharper警告:在闭包中访问foreach变量。使用不同版本的编译器编译时可能会有不同的行为。如何解决:在关闭resharper警告中访问foreach变量?

这是我在做什么:

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

我的扩展如下:

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

注意这是按预期工作,但我如何才能避免这样的警告?
我会感谢您提供的任何帮助。

+2

为什么你使用'Expression <>'如果你所做的全部是调用'.Compile()'?为什么不直接使用'Func <>'? – hvd

+0

你为什么要传递一个表达式,而不仅仅是一个布尔? –

+0

@ChaosPandion:这对我很有帮助,因为我不需要在我的视图中使用if。 – Esteban

回答

25

块范围变量应该解决警告。

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

谢谢,它修复了警告,为什么会发生这种情况? – Esteban

+10

@Esteban JetBrains wiki上有更多的[这里](这取决于你的R#版本可能直接从灯泡菜单为'为什么ReSharper暗示这一点?另见[这个SO问题](http://stackoverflow.com/questions/235455/access-to-modified-closure?rq=1) – AakashM

+2

@Esteban这是迄今为止我找到的最好的解释:http:// stackoverflow。 COM /问题/ 14907987 /访问到的foreach可变的闭合 – ForceMagic

2

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