簡體   English   中英

使用泛型類型參數傳遞和轉換Func

[英]Passing and casting Func with generic type parameters

我想將帶有泛型參數的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?

    }

}

您能否建議如何實現這一目標,或者可以采用其他方法來實現?

僅使用閉包而不是嘗試處理將值作為參數傳遞會更容易:

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