英文:
How do I define a Func where it may be async
问题
我正在编写一个方法,该方法将接收一个参数,如下所示:
ShowMessagePopupAsync(string header, string message, Func<string, Task> onClick, Func<Task>? onClose)
首先,onClose
可能为 null,因此有 ?
。
但是我应该如何声明 Func
的返回值呢?它可以是一个异步方法,在 OnClick
中的代码需要使用 await 并返回一个 Task。或者它可能只是保存传递的字符串并设置一个布尔值。
为了处理这两种情况,我的参数应该是什么呢?
public void OnClick(string message) {
savedMessage = message;
}
public async Task<void> OnClick(string message) {
var x = await SaveTheInfo(message);
if (x > 3)
await CallSomeone();
}
英文:
I am writing a method where it will get a parameter like this:
ShowMessagePopupAsync(string header, string message, Func<string, Task> onClick, Func<Task>? onClose)
First off, onClose
may be null hence the ?
.
But how should I declare the return value of the Func
? It could be an async method where the code on the OnClick
needs to use await and return a Task. Or it may be as simple as saving the passed string and setting a bool.
What should my parameter be to handle both of these?
public void OnClick(string message) {
savedMessage = message;
}
public async Task<void> OnClick (string message) {
var x = await SaveTheInfo (message);
if (x > 3)
await CallSomeone();
}
答案1
得分: 1
You can change the first method to look like this:
public Task OnClick(string message) {
savedMessage = message;
return Task.CompletedTask;
}
This first one doesn't have anything that needs to execute asynchronously, so you can just skip the async
keyword and return Task.CompletedTask
, which is useful for scenarios like this.
public async Task OnClick(string message) {
var x = await SaveTheInfo(message);
if (x > 3)
await CallSomeone();
}
This second one can stay the way it is. You just don't need the Task<void>
in the signature because it's essentially the same as Task
.
When two methods share the exact same signature, they cannot exist in the same class. In this case, both methods do share the same signature, the async
keyword does not make a difference because the compiler removes it.
英文:
You can change the first method to look like this:
public Task OnClick(string message) {
savedMessage = message;
return Task.CompletedTask;
}
This first one doesn't have anything that needs to execute asynchronously, so you can just skip the async
keyword and return Task.CompletedTask
, which is useful for scenarios like this.
public async Task OnClick(string message) {
var x = await SaveTheInfo(message);
if (x > 3)
await CallSomeone();
}
This second one can stay the way it is. You just don't need the Task<void>
in the signature, because it's essentially the same as Task
.
When two methods share the exact same signature, they cannot exist in the same class. In this case, both methods do share the same signature, the async
keyword does not make a difference, because the compiler removes it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论