2009-06-26 6 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まだ割り当てられていません。もちろん、コンパイラはクロージャーにそれを持ち上げるので、とにかくOKです - コンパイラは、警告を出すときにコンパイラがそれをどのように変更するのか分からないと思います。 –

0

"割り当てられていない変数の使用"エラーが発生する理由は、コンパイラが実際にコードを生成する方法が原因です。デリゲート{}構文を使用すると、実際のメソッドがコンパイラによって作成されます。デリゲートの添付フィールドを参照しているので、コンパイラはローカル変数attachを生成されたデリゲートメソッドに渡そうとします。

ここでそれをより明確に役立つはずおおよそ変換されたコードです:それは初期化される前、それは_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 
    } 
} 

お知らせ。

関連する問題