我想将带有通用参数的 func 传递给 BackgroundWorker,但我偶然发现了如何在另一端强制转换和运行 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?
}
}
您能建议如何实现这一目标,或者可能采用不同的方法吗?