繁体   English   中英

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

[英]How ASP.NET Core APIs convert ActionResult<T> to T in action methods

作为示例,请查看以下代码,这是一个API操作:

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

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

这是可能的,因为称为运算符重载的语言功能允许创建自定义运算符。 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);
       }
}

public static implicit operator即此方法为TValue提供了隐式转换为ActionResult类型的逻辑。 这是一个非常简单的方法,它创建一个新的ActionResult ,其值设置为一个名为Value的公共变量。 这种方法使这个合法:

ActionResult<int> result = 10; <-- // same as new ActionResult(10)

这基本上为你在Action方法中做的合法创造了合成糖。

暂无
暂无

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

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