2012-09-22 2 views
25

ReSharper 경고 : 클로저에서 foreach 변수에 액세스. 다른 버전의 컴파일러으로 컴파일 할 때 다른 동작이 발생할 수 있습니다. 예상대로이 작동하고해결 방법 : closure resharper 경고에서 foreach 변수에 액세스합니까?

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

참고하지만 어떻게 내가이 경고를 방지 할 수 있습니다 다음과 같이

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

내 확장은 다음과 같습니다

이것은 내가 뭘 무엇인가?
제공되는 도움말에 감사드립니다.

+2

'Expression <>'을 사용하는 이유는 그것으로'.Compile()'을 호출하는 이유가 무엇입니까? 'Func <>'을 직접 쓰지 않는 이유는 무엇입니까? – hvd

+0

왜 bool 대신 표현식을 전달하는 것입니까? –

+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 [여기] (http://confluence.jetbrains.net/display/ReSharper/Access+to+modified+closure) (R #의 버전에 따라 'ReSharper가 왜 이것을 제안하고있는가?'와 같은 전구 메뉴; 또한 [이 질문에] 참조 (http://stackoverflow.com/questions/235455/access-to-modified-closure?rq=1) – AakashM

+2

@Esteban 그게 내가 지금까지 찾은 최고의 설명이다 : http : // stackoverflow. co.kr/questions/14907987/foreach-variable-in-closure에 대한 액세스 – ForceMagic

2

또 다른 옵션은 DisplayBooleanFor 방법에 JetBrains.Annotations.InstantHandleAttribute 특성을 적용하는 것입니다.

관련 문제