2012-08-06 2 views
8

클래스의 진행률 개체를 처음 초기화하는 데 느린 로딩을 사용하려고합니다. 그러나, 나는 다음과 같은 오류 받고 있어요 :게으른 <T> 지연로드 오류 : 필드 초기화 프로그램이 비 정적 필드, 메서드 또는 속성을 참조 할 수 없습니다.

A field initializer cannot reference the non-static field, method, or property.

private Lazy<Progress> m_progress = new Lazy<Progress>(() => 
{ 
    long totalBytes = m_transferManager.TotalSize(); 
    return new Progress(totalBytes); 
}); 

는 .NET 2.0에서, 나는 다음을 수행 할 수 있습니다,하지만 난 날짜 접근 방식까지 더 사용하는 것을 선호 :

private Progress m_progress; 
private Progress Progress 
{ 
    get 
    { 
     if (m_progress == null) 
     { 
      long totalBytes = m_transferManager.TotalSize(); 
      m_progress = new Progress(totalBytes); 
     } 
     return m_progress; 
    } 
} 

아무도 도와 줄 수 있습니까?

감사합니다.

답변

20

해당 초기화 프로그램에서는 this이 캡처 클래스로 전달되어야하고 this은 필드 초기화 프로그램에서 사용할 수 없습니다. 게으른 초기화가 null 반환 할 수

+0

대단히 감사합니다 :) – bobbo

+0

P, 그리고, 개인적으로

private readonly Lazy<Progress> m_progress; public MyType() { m_progress = new Lazy<Progress>(() => { long totalBytes = m_transferManager.TotalSize(); return new Progress(totalBytes); }); } 

가, 난 그냥 비록 get 접근을 사용하십시오 : 그러나, 생성자에서 볼 수 있습니다 여전히 초기화됩니다. 이 경우 getter 속성은 반복해서 초기화하려고합니다. – wensveen

+0

@wensveen 아니, 그렇지 않을거야 : https://gist.github.com/mgravell/b547455bb4afe25cdae44d8cc78b8bdd –

관련 문제