c#通用函数作为参数

时间:2016-05-13 10:28:40

标签: c# generics

我有这个功能:

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

但显然这不起作用。 有谁知道我怎么能做到这一点?

3 个答案:

答案 0 :(得分:5)

这是你需要的:

    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");

答案 1 :(得分:2)

您正在尝试创建一个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 :(得分:1)

我可以看到两种可能性:

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