【发布时间】: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<>,你为什么要使用.Compile()?为什么不直接使用Func<>? -
你为什么要传入一个表达式而不是一个布尔值?
-
@ChaosPandion:这对我很有帮助,因为我不需要在我的视图中使用 if。
-
@KellyEthridge:因为我想做一个 DisplayBooleanFor 而不是 DisplayBoolean。