简体   繁体   English

Ok()如何兼具任务 <IActionResult> 和IActionResult?

[英]How can Ok() be both Task<IActionResult> and IActionResult?

In a Controller in .NET Core you can return Ok() as an IActionResult . 在.NET Core中的Controller中,您可以将Ok()作为IActionResult But I do not understand how it can also return a Task<IActionResult> . 但是我不明白它怎么也可以返回Task<IActionResult>

Example: 例:

    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() returns a OkResult , which in turn implements IActionResult . Ok()返回一个OkResult ,后者进而实现IActionResult How does .NET know how to handle it (without awaiting) if the method signature is returning a Task<IActionResult> ? 如果方法签名返回Task<IActionResult> ,.NET如何知道如何处理(不等待)?

The async keyword causes the compiler to take care of this automatically. async关键字使编译器自动执行此操作。 Async methods implicitly "wrap" the return value in a Task. 异步方法隐式“包装”任务中的返回值。

async Task<int> GetNumber()
{
    return 42;
}

vs

Task<int> GetNumber()
{
    return Task.FromResult(42);
}

The async keyword is a shorthand that wraps the contents of the method in a Task. async关键字是将方法的内容包装在Task中的简写形式。 When you return inside an async method the compiler wraps it up into a Task for you. 当您在异步方法内部返回时,编译器会为您包装成一个Task。 For example these two methods are essentially the same: 例如,这两种方法本质上是相同的:

private static Task<string> Hello()
{
    return new Task<string>(() => "hello");
} 

private static async Task<string> AsyncHello()
{
    return "hello";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM