gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:21:22 25 4
gpt4 key购买 nike

作为示例,请看下面的代码,它是一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com