我有 func<Task>
我的项目中的代表可以为空。有没有办法让这样的代表的调用更简单,如下所示?
public async Task Test()
{
Func<Task> funcWithTask = null;
await (funcWithTask != null ? funcWithTask.Invoke() : Task.CompletedTask);
}
最佳答案
Is there any way to make the call of such a delegate simpler as displayed below?
有替代方案:
if (funcWithTask != null) await funcWithTask();
或者:await (funcWithTask?.Invoke() ?? Task.CompletedTask);
第二个使用 null-conditional operator ?.
, 只调用 Invoke()
当funcWithTask
不为空,null-coalescing operator ??
当左侧操作数为空时返回右侧操作数(在这种情况下为 Task.CompletedTask
)。
关于c# - 如何使用 await 简单安全地调用可为空的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67623315/