简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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