[英]c# Generic function as a parameter
I have this function: 我有这个功能:
private async Task Wizardry<T>(Func<T theParameter, Task> method)
{
try
{
await method(theParameter);
}
catch
{ }
}
and the way I see it working is like this: 我看到它工作的方式是这样的:
await this.Wizardry<Email>(this.emailProvider.SendAsync(email));
await this.Wizardry<Log>(this.SaveLog(log));
but obviously that does not work. 但显然那行不通。 Does anyone know how I can achieve this? 有谁知道我怎么能做到这一点?
Is this what you need: 这是您需要的吗?
private async Task Wizardry<T>(Func<T, Task> method, T theParameter)
{
try
{
await method(theParameter);
}
catch
{
}
}
And invoke it like: 并像这样调用它:
await this.Wizardry<string>((z)=> Task.Run(()=>Console.WriteLine(z)), "test");
You are attempting to create a Func
where you want to pass in parameters while you haven't got any parameters to pass in. 您正在尝试创建一个Func
,您想在其中传递参数而又没有传递任何参数的地方。
A non-generic Func<Task>
will do: 非泛型Func<Task>
将执行以下操作:
await this.Wizardry(() => this.emailProvider.SendAsync(email));
await this.Wizardry(() => this.SaveLog(log));
private async Task Wizardry(Func<Task> method)
{
await method();
}
I can see 2 possibilities: 我可以看到2种可能性:
private async Task Wizardry(Func<Task> method) {
try {
await method();
} catch {
}
}
Which is called with: 称为:
this.Wizardry(() => this.emailProvider.SendAsync(email));
Or 要么
private async Task Wizardry<T>(Func<T, Task> method, T theParameter) {
try {
await method(theParameter);
} catch {
}
}
Which is called with: 称为:
this.Wizardry(this.emailProvider.SendAsync, email);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.