ASP.NET Core API如何在操作方法中将ActionResult <T>转换为T

Mus*_*aie 3 c# .net-core

作为示例,请看下面的代码,它是一个API动作:

[HttpGet("send")]
public ActionResult<string> Send()
{
    if (IsAuthorized())
    {
        return "Ok";
    }
    return Unauthorized(); // is of type UnauthorizedResult -> StatusCodeResult -> ActionResult -> IActionResult
}
Run Code Online (Sandbox Code Playgroud)

我的问题是这种数据转换是如何发生的?编译器如何不会失败?

Avi*_*ish 6

由于称为运算符重载的语言功能允许创建自定义运算符,因此这是可能的。ActionResult具有这样的实现

public sealed class ActionResult<TValue> : IConvertToActionResult
{
       public TValue Value { get; }

       public ActionResult(TValue value)
       {
            /* error checking code removed */
            Value = value;
       }

       public static implicit operator ActionResult<TValue>(TValue value)
       {
           return new ActionResult<TValue>(value);
       }
}
Run Code Online (Sandbox Code Playgroud)

public static implicit operator即,该方法提供的逻辑TValue隐式浇铸型的ActionResult。这是一个非常简单的方法,可以使用ActionResult设置为名为的公共变量的值来创建一个新值Value。此方法使此合法:

ActionResult<int> result = 10; <-- // same as new ActionResult(10)
Run Code Online (Sandbox Code Playgroud)

本质上来说,这是使您在Action方法中所做的操作合法的语法糖。