gpt4 book ai didi

c# - Ok() 怎么可能既是 Task 又是 IActionResult?

转载 作者:太空宇宙 更新时间:2023-11-03 19:47:28 25 4
gpt4 key购买 nike

Controller 中在 .NET Core 中你可以返回 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com