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

标签 c# .net-core

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

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

我的问题是这里是如何进行数据转换的?编译器如何不失败?

最佳答案

这是可能的,因为一种称为运算符重载的语言特性允许创建自定义运算符。 ActionResult 有这样一个 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 implicit operator 即此方法为 TValue 提供了隐式转换为类型 ActionResult 的逻辑。这是一个非常简单的方法,它创建一个新的 ActionResult,并将值设置为一个名为 Value 的公共(public)变量。此方法使此合法:

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

这实质上为您在 Action 方法中所做的合法行为创建了语法糖。

关于c# - ASP.NET Core API 如何在操作方法中将 ActionResult<T> 转换为 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56513377/

相关文章:

c# - 保持 Dotnet Core Grpc Server 作为控制台应用程序运行?

c# - 使用事件处理程序动态加载用户控件 - 注销

c# - AOP 性能开销

c# - 基于 TPL 的循环服务 : right worker method signature, 异步

testing - 在 VS2017 中使用 xUnit 测试 .NET Core 2.0 类库时如何设置 ASPNETCORE_ENVIRONMENT

asp.net-mvc - 如何在 ASP.NET Core 的 Razor Pages 中设置全局变量?

c# - 如何模拟返回 List<T> 的方法?

c# - Asp .NET 从 tar.gz 存档中读取文件

c# - 如何列出 ASP.NET Core 中的所有配置源或属性?

c# - 我可以为 Azure Functions 绑定(bind)表达式配置默认值吗?