1
我想將通用函數的func參數傳遞給BackgroundWorker,但我偶然發現如何在另一端投射和運行func。傳遞和使用泛型類型參數鑄造Func
以下代碼演示了我正在嘗試執行的操作。注意我在所有Execute
方法中有兩個約束,BackgroundExecutionContext
和BackgroundExecutionResult
,我需要能夠採用更多的一個通用參數。
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?
}
}
你可以建議如何實現這個或者可能採用不同的方法?
這真棒。謝謝,@Servy。 – Eric