2013-10-09 65 views
1

我想將通用函數的func參數傳遞給BackgroundWorker,但我偶然發現如何在另一端投射和運行func。傳遞和使用泛型類型參數鑄造Func

以下代碼演示了我正在嘗試執行的操作。注意我在所有Execute方法中有兩個約束,BackgroundExecutionContextBackgroundExecutionResult,我需要能夠採用更多的一個通用參數。

public static class BackgroundExecutionProvider 
{ 

    public static void Execute<TValue, TResult>(Func<TValue, TResult> fc) 
     where TValue: BackgroundExecutionContext 
     where TResult: BackgroundExecutionResult 
    { 
     var bw = new BackgroundWorker(); 
     bw.DoWork += new DoWorkEventHandler(Worker_DoWork); 

     bw.RunWorkerAsync(fc); 
    } 

    public static void Execute<TValue, T1, TResult>(Func<TValue, T1, TResult> fc) 
     where TValue : BackgroundExecutionContext 
     where TResult : BackgroundExecutionResult 
    { 
     var bw = new BackgroundWorker(); 
     bw.DoWork += new DoWorkEventHandler(Worker_DoWork); 

     bw.RunWorkerAsync(fc); 
    } 

    public static void Execute<TValue, T1, T2, TResult>(Func<TValue, T1, T2, TResult> fc) 
     where TValue : BackgroundExecutionContext 
     where TResult : BackgroundExecutionResult 
    { 
     var bw = new BackgroundWorker(); 
     bw.DoWork += new DoWorkEventHandler(Worker_DoWork); 

     bw.RunWorkerAsync(fc); 
    } 

    private static void Worker_DoWork(object sender, DoWorkEventArgs e) 
    { 

     // How do I cast the EventArgs and run the method in here? 

    } 

} 

你可以建議如何實現這個或者可能採用不同的方法?

回答

2

它很容易,只需使用的,而不是試圖處理傳遞值作爲參數關閉:

public static void Execute<TValue, TResult>(Func<TValue, TResult> fc) 
    where TValue : BackgroundExecutionContext 
    where TResult : BackgroundExecutionResult 
{ 
    var bw = new BackgroundWorker(); 
    bw.DoWork += (_, args) => 
    { 
     BackgroundExecutionContext context = GetContext(); //or however you want to get your context 
     var result = fc(context); //call the actual function 
     DoStuffWithResult(result); //replace with whatever you want to do with the result 
    }; 

    bw.RunWorkerAsync(); 
} 
+0

這真棒。謝謝,@Servy。 – Eric