2009-06-26 9 views
2

위임 된 작업을 다른 기능에서 분리하는 대신 인라인 할 수있는 방법이 있습니까?함수 대리자에게 함수를 인라인 할 수 있고 동시에 참조 할 수있는 방법이 있습니까?

원본 코드 :이 작동합니다 생각

private void ofdAttachment_FileOk(object sender, CancelEventArgs e) 
    { 

     Action attach = delegate 
     { 
      if (this.InvokeRequired) 
      { 
       // but it has compilation here 
       // "Use of unassigned local variable 'attach'" 
       this.Invoke(new Action(attach)); 
      } 
      else 
      { 
       // attaching routine here 
      } 
     }; 

     System.Threading.ThreadPool.QueueUserWorkItem((o) => attach()); 
    } 

답변

4

:

private void ofdAttachment_FileOk(object sender, CancelEventArgs e) 
{ 

    Action attach = null; 
    attach = delegate 
    { 
     if (this.InvokeRequired) 
     { 
      // since we assigned null, we'll be ok, and the automatic 
      // closure generated by the compiler will make sure the value is here when 
      // we need it. 
      this.Invoke(new Action(attach)); 
     } 
     else 
     { 
      // attaching routine here 
     } 
    }; 

    System.Threading.ThreadPool.QueueUserWorkItem((o) => attach()); 
} 

private void ofdAttachment_FileOk(object sender, CancelEventArgs e) 
    {    
     System.Threading.ThreadPool.QueueUserWorkItem((o) => Attach()); 
    } 

    void Attach() // I want to inline this function on FileOk event 
    { 

     if (this.InvokeRequired) 
     { 
      this.Invoke(new Action(Attach)); 
     } 
     else 
     { 
      // attaching routine here 
     } 
    } 

나는이 같은 (별도의 함수를 만들 필요) 할 수 없습니다 싶어

익명 메소드를 선언하는 행 앞에 'attach'(null 작동) 값을 지정하기 만하면됩니다. 나는 이전이 조금 이해하기 더 쉽다고 생각한다.

+0

감사합니다.^_^조금 비웃음을 받았는데 왜 C#이 할당되지 않은 것으로 감지했는지 – Hao

+0

런타임에 할당의 오른쪽이 왼쪽보다 먼저 평가됩니다. 따라서이 경고를 담당하는 컴파일러 부분은 우리가 할당 한 행의 표현식 오른쪽에서 변수의 값을 사용하려고한다는 것을 알 수 있습니다. 따라서 RHS의 평가 중에 hasn 아직 배정되지 않았습니다. 물론, 컴파일러는 그것을 클로저로 들여 올 것이므로, 어쨌든 괜찮을 것입니다. 컴파일러는 경고를 내보낼 때 컴파일러가 그것을 어떻게 수정할지 알지 못합니다. –

0

"할당되지 않은 변수 사용"오류가 발생하는 이유는 컴파일러가 실제로 코드를 생성하는 방식 때문입니다. 위임 {} 구문을 사용하면 컴파일러에서 실제 메서드를 만들 수 있습니다. 델리게이트의 연결된 필드를 참조하기 때문에 컴파일러는 로컬 변수 attach을 생성 된 대리자 메서드에 전달하려고 시도합니다.

여기 수 있도록 도움이 대략 번역 코드의 IT 명확 :

그것을 초기화 것 전에이 _B에 <> _1 방법을 필드를 첨부 통과 있다고
private void ofdAttachment_FileOk(object sender, CancelEventArgs e) 
{ 

    Action attach = _b<>_1(attach); 

    System.Threading.ThreadPool.QueueUserWorkItem((o) => attach()); 
} 

private Action _b<>_1(Action attach) 
{ 
    if (this.InvokeRequired) 
    { 
     // but it has compilation here 
     // "Use of unassigned local variable 'attach'" 
     this.Invoke(new Action(attach)); 
    } 
    else 
    { 
     // attaching routine here 
    } 
} 

알 수 있습니다.