我收到了這個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");
}
注意這是按預期工作,但我如何才能避免這樣的警告?
我會感謝您提供的任何幫助。
爲什麼你使用'Expression <>'如果你所做的全部是調用'.Compile()'?爲什麼不直接使用'Func <>'? – hvd
你爲什麼要傳遞一個表達式,而不僅僅是一個布爾? –
@ChaosPandion:這對我很有幫助,因爲我不需要在我的視圖中使用if。 – Esteban