[英]How ASP.NET Core APIs convert ActionResult<T> to T in action methods
As an example look at below code which is a an API action: 作为示例,请查看以下代码,这是一个API操作:
[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?
编译器如何失败?
This is possible due to a language feature called operator overloading which allows for the creation of custom operators. 这是可能的,因为称为运算符重载的语言功能允许创建自定义运算符。 ActionResult has such an implementation :
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
Ie this method provides the logic for TValue
to be implicitly casted to type ActionResult. public static implicit operator
即此方法为TValue
提供了隐式转换为ActionResult类型的逻辑。 It's a very simple method that creates a new ActionResult
with the value set to a public variable called Value
. 这是一个非常简单的方法,它创建一个新的
ActionResult
,其值设置为一个名为Value
的公共变量。 This method makes this legal: 这种方法使这个合法:
ActionResult<int> result = 10; <-- // same as new ActionResult(10)
This essentially creates syntatic sugar for what you do in the Action methods to be legal. 这基本上为你在Action方法中做的合法创造了合成糖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.