作为示例,请看下面的 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
IE。该方法提供了逻辑TValue
to be 隐含地转换为 ActionResult 类型。这是一个非常简单的方法,可以创建一个新的ActionResult
将值设置为名为的公共变量Value
。此方法使此合法:
ActionResult<int> result = 10; <-- // same as new ActionResult(10)
这实质上为您在 Action 方法中所做的事情创建了语法糖,使其合法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)