ASP.NET Core 如何将任何类型转换为控制器操作的 ActionResult<T>

我在 ASP.NET Core 2.2 的 WebApi 控制器中有一个简单的操作,看起来像这样:


[HttpGet("test123")]

public ActionResult<string> Test123()

{

    return new OkResult();

}

这编译得很好,但我想知道OkResult对象怎么可能被转换成ActionResult<string>?


这些类有不同的继承链: OkResult -> StatusCodeResult -> ActionResult 虽然ActionResult<TValue>只是实现IConvertToActionResult ,换句话说,ActionResult<string>不是OkResult类的基类型。


如果我手动执行此操作并将代码更改为:


[HttpGet("test123")]

public ActionResult<string> Test123()

{

    var a = new OkResult();

    var b = a as ActionResult<string>;  // Error CS0039


    return b;

}

代码不会因转换错误而编译:


错误 CS0039:无法通过引用转换、装箱转换、拆箱转换、包装转换或空类型转换将类型“Microsoft.AspNetCore.Mvc.OkResult”转换为“Microsoft.AspNetCore.Mvc.ActionResult”


第一个代码工作而第二个代码不工作怎么可能?如何从没有公共基类型的对象转换返回类型?


繁星点点滴滴
浏览 76回答 2
2回答

慕勒3428872

以下两个隐式运算符来自ActionResult<TValue>/// <summary>/// Implictly converts the specified <paramref name="value"/> to an <see cref="ActionResult{TValue}"/>./// </summary>/// <param name="value">The value to convert.</param>public static implicit operator ActionResult<TValue>(TValue value){&nbsp; &nbsp; return new ActionResult<TValue>(value);}/// <summary>/// Implictly converts the specified <paramref name="result"/> to an <see cref="ActionResult{TValue}"/>./// </summary>/// <param name="result">The <see cref="ActionResult"/>.</param>public static implicit operator ActionResult<TValue>(ActionResult result){&nbsp; &nbsp; return new ActionResult<TValue>(result);}是什么允许在操作中使用多个返回类型。[HttpGet("test123")]public ActionResult<string> Test123() {&nbsp; &nbsp; if(someCondition) return "String value"; //<--String&nbsp; &nbsp; return Ok(); //<-- OkResult}当返回字符串时,ActionResult<TValue>(TValue value)调用运算符,返回ActionResult<TValue>另一个运算符的有效值,反之亦然。

回首忆惘然

您的第一个示例利用隐式用户定义类型转换运算符,如下所示:public static implicit operator ActionResult<TValue>(ActionResult result){&nbsp; &nbsp; return new ActionResult<TValue>(result);}您的第二个示例 usingas无法使用隐式转换运算符,因为根据文档,它:...仅执行引用转换、可空转换和装箱转换。as 运算符不能执行其他转换,例如用户定义的转换,而应使用强制转换表达式来执行这些转换。
打开App,查看更多内容
随时随地看视频慕课网APP