ASP.NET Core API 如何转换 ActionResult<T>到 T in action 方法 [英] How ASP.NET Core APIs convert ActionResult&lt;T&gt; to T in action methods

查看:14
本文介绍了ASP.NET Core API 如何转换 ActionResult<T>到 T in action 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下面的代码为例,这是一个 API 操作:

As an example look at below code which is a an API action:

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

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

My question is how this data conversion is happening here? How doesn't the compiler fail?

推荐答案

这是可能的,因为有一种称为运算符重载的语言特性,它允许创建自定义运算符.ActionResult 有这样一个实现:

This is possible due to a language feature called operator overloading which allows for the creation of custom operators. ActionResult has such an implementation:

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 隐式运算符 即此方法为 TValue 提供逻辑,以隐式强制转换为类型 ActionResult.这是一个非常简单的方法,它创建一个新的 ActionResult,并将值设置为一个名为 Value 的公共变量.这种方法使这合法:

public static implicit operator I.e. this method provides the logic for TValue to be implicitly casted to type ActionResult. It's a very simple method that creates a new ActionResult with the value set to a public variable called Value. This method makes this legal:

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

这实际上为您在 Action 方法中所做的合法操作创建了语法糖.

This essentially creates syntatic sugar for what you do in the Action methods to be legal.

这篇关于ASP.NET Core API 如何转换 ActionResult<T>到 T in action 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆