【问题标题】:How do I fix: Access to foreach variable in closure resharper warning?如何修复:在闭包 resharper 警告中访问 foreach 变量?
【发布时间】:2012-09-14 20:30:38
【问题描述】:

我收到了这个 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");
}

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

【问题讨论】:

  • 如果你只使用Expression&lt;&gt;,你为什么要使用.Compile()?为什么不直接使用Func&lt;&gt;
  • 你为什么要传入一个表达式而不是一个布尔值?
  • @ChaosPandion:这对我很有帮助,因为我不需要在我的视图中使用 if。
  • @KellyEthridge:因为我想做一个 DisplayBooleanFor 而不是 DisplayBoolean。
  • Access to Modified Closure (2) 的可能重复项

标签: c# resharper


【解决方案1】:

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

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

【讨论】:

  • 谢谢,它修复了警告,知道为什么会这样吗?
  • @Esteban 在 JetBrains wiki here 上有更多内容(根据您的 R# 版本,可能会直接从灯泡菜单链接为“为什么 ReSharper 建议这样做?);另见this SO question
  • @Esteban 这是迄今为止我发现的最好的解释:stackoverflow.com/questions/14907987/…
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2010-12-13
    • 2023-03-21
    • 1970-01-01
    • 2011-02-26
    • 2011-07-17
    • 2015-11-08
    • 2018-08-31
    • 2011-12-22
    • 2013-09-22
    相关资源
    最近更新 更多