在.NET Core中的Controller
中,您可以将Ok()
作为IActionResult
返回。但是我不明白它怎么也可以返回Task<IActionResult>
。
例:
public class FooController : Controller
{
[HttpGet]
public async Task<IActionResult> OkResultAsync()
{
// This is ok. But I don't get why since OkResult != Task<IActionResult>
OkResult result = Ok();
return result;
}
[HttpGet]
public IActionResult OkResult()
{
// This is ok, and it seems logical since OkResult implements IActionResult.
OkResult result = Ok();
return result;
}
[HttpGet]
public FooResult Bar()
{
// This is ok.
return new FooResult();
}
[HttpGet]
public async Task<FooResult> BarAsync()
{
// This is not ok since FooResult != Task<FooResult>
return new FooResult();
}
}
Ok()
返回一个OkResult
,而该实现了IActionResult
。如果方法签名返回Task<IActionResult>
,. NET如何知道如何处理(不等待)? 最佳答案
async
关键字使编译器自动进行此处理。异步方法隐式“包装”任务中的返回值。
async Task<int> GetNumber()
{
return 42;
}
与
Task<int> GetNumber()
{
return Task.FromResult(42);
}
关于c# - Ok()如何同时是Task <IActionResult>和IActionResult?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43654829/