使用泛型类型参数传递和强制转换 Func

本文关键字:转换 Func 泛型类型 参数传递 | 更新日期: 2023-09-27 18:34:42

我想将带有通用参数的func传递给BackgroundWorker 但是我偶然发现了如何在另一端转换和运行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?
    }
}

您能否建议如何实现这一目标,或者使用不同的方法?

使用泛型类型参数传递和强制转换 Func

只使用闭包比尝试处理将值作为参数传递更容易:

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();
}