繁体   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