简体   繁体   English

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

[英]Passing and casting Func with generic type parameters

I would like to pass func with generic parameters to a BackgroundWorker but I'm stumbled upon on how to cast and run the func at the other end. 我想将带有泛型参数的func传递给BackgroundWorker,但我偶然发现了如何在另一端强制转换和运行func。

The following code demonstrates what I'm trying to do. 以下代码演示了我正在尝试做的事情。 Notice I have two constraints in all Execute methods, BackgroundExecutionContext and BackgroundExecutionResult , and I need to able to take more that one generic parameters. 注意,我在所有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?

    }

}

Can you suggest how to achieve this or maybe with a different approach? 您能否建议如何实现这一目标,或者可以采用其他方法来实现?

It's easier to just use a closure instead of trying to deal with passing the value as a parameter: 仅使用闭包而不是尝试处理将值作为参数传递会更容易:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM