2016-10-06 15 views
1

내 함수는 내가 브레이크 포인트를 넣어 나는 결과 노드가 항복 볼 수 있습니다 확인중단 점 수율 리턴와 방법에 트리거되지

IEnumerable<IPublishedContent> GetAllowedBlogs(IEnumerable<IPublishedContent> blogLandingNodes) 
{ 
    foreach (var node in blogLandingNodes) 
    { 
     if ("Condition") 
     { 
      var blogsToDisplay = GetPostsForBlog(node); 

      foreach (var blog in blogsToDisplay) 
      { 
       yield return blog; 
      } 
     } 
     else 
     { 
      var blogsToDisplay = GetPostsForBlog(node, catId); 

      foreach (var blog in blogsToDisplay) 
      { 
       yield return blog; 
      } 
     } 
    } 
} 

,하지만 난 여기에 확인

IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node); 
같다

나는 아무것도 얻지 못합니다. 내가 잘못하고있는 것은 무엇입니까?

+2

'GetAllowedBlogs()'는 _iterator_ 만 반환합니다. 내부의 코드는 컴파일러에 의해 상태 머신으로 변환되며 iterator_를 사용하는 경우에만 실행됩니다 (예 :'posts1'에'foreach '가있는 경우). –

+0

당신은 무엇을 "확인"하고 어떻게합니까? –

+2

좋은 설명은 [here] (http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx) 및 [here] (http://www.codeproject.com/Tips/359873/Csharp-Iterator)에서 찾을 수 있습니다. - 패턴 - demystified) –

답변

2

모든 '수익자'가 게으른 열거로 변환 되었기 때문입니다.

IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node); 

이 줄은 블로그의 열거를 만들지 만 그것을을 실행하지 않습니다.
아직 실제로 실행되지 않았습니다.

이 하나를 시도하고 볼 중단 점을 일 경우 : 참고로

IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node).ToList(); 

(.ToList 물론을 System.Linq 네임 스페이스입니다)

:이 질문의 요점 없지만 yield이 실제로 컴파일되는 것을 보는 것이 흥미로울 수 있습니다. 이 링크 아래의 코드와 설명은 조금 오래되었지만 주요 사항은 계속 적용됩니다. http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx

0

지연 평가.

posts1을 사용하기 시작할 때까지 코드를 실행하지 않습니다.

0

실제로 코드를 실행할 ToList ToArray 등의 메소드 중 하나를 호출하여 시퀀스를 구체화해야합니다.