![](/img/trans.png)
[英]How is ASP.NET Core able to convert any type to ActionResult<T> return type of controller actions?
[英]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.