簡體   English   中英

c#泛型函數作為參數

[英]c# Generic function as a parameter

我有這個功能:

private async Task Wizardry<T>(Func<T theParameter, Task> method)
{
    try
    {
        await method(theParameter);
    }
    catch
    { }
}

我看到它工作的方式是這樣的:

await this.Wizardry<Email>(this.emailProvider.SendAsync(email));
await this.Wizardry<Log>(this.SaveLog(log));

但顯然那行不通。 有誰知道我怎么能做到這一點?

這是您需要的嗎?

    private async Task Wizardry<T>(Func<T, Task> method, T theParameter)
    {
        try
        {
            await method(theParameter);
        }
        catch
        {
        }
    }

並像這樣調用它:

await this.Wizardry<string>((z)=> Task.Run(()=>Console.WriteLine(z)), "test");

您正在嘗試創建一個Func ,您想在其中傳遞參數而又沒有傳遞任何參數的地方。

非泛型Func<Task>將執行以下操作:

await this.Wizardry(() => this.emailProvider.SendAsync(email));
await this.Wizardry(() => this.SaveLog(log));

private async Task Wizardry(Func<Task> method)
{
    await method();
}

我可以看到2種可能性:

private async Task Wizardry(Func<Task> method) {
    try {
        await method();
    } catch {
    }
}

稱為:

this.Wizardry(() => this.emailProvider.SendAsync(email));

要么

private async Task Wizardry<T>(Func<T, Task> method, T theParameter) {
    try {
        await method(theParameter);
    } catch {
    }
}

稱為:

this.Wizardry(this.emailProvider.SendAsync, email);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM