我在ASP.NET Core 2.2中的WebApi控制器中有一个简单的操作,如下所示:
I have simple action in WebApi controller in ASP.NET Core 2.2 that looks like this:
[HttpGet("test123")] public ActionResult<string> Test123() { return new OkResult(); }这可以很好地编译,但是我想知道如何将 OkResult 对象转换为 ActionResult< string> ?
This compiles fine but I am wondering how is it possible that OkResult object is converted to ActionResult<string>?
这些类具有不同的继承链: OkResult->StatusCodeResult->ActionResult 而 ActionResult< TValue> 仅实现 IConvertToActionResult 换句话说, ActionResult< string> 不是 OkResult 类的基本类型.
These classes have different inheritance chain: OkResult -> StatusCodeResult -> ActionResult while ActionResult<TValue> only implements IConvertToActionResult In other words, ActionResult<string> is not base type for OkResult class.
如果我手动执行此操作并将代码更改为:
If I do that manually and change code to:
[HttpGet("test123")] public ActionResult<string> Test123() { var a = new OkResult(); var b = a as ActionResult<string>; // Error CS0039 return b; }代码不会编译,并显示转换错误:
the code wont compile with the conversion error:
错误CS0039:无法通过引用转换,装箱转换,拆箱转换,换行转换或空类型转换将类型"Microsoft.AspNetCore.Mvc.OkResult"转换为"Microsoft.AspNetCore.Mvc.ActionResult"
Error CS0039: Cannot convert type 'Microsoft.AspNetCore.Mvc.OkResult' to 'Microsoft.AspNetCore.Mvc.ActionResult' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
第一个代码如何工作而第二个代码却不工作呢?如何从没有通用基本类型的对象转换返回类型?
How is it possible that first code works while the second doesn't? How is return type converted from objects that don't have common base type?
推荐答案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) { 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) { return new ActionResult<TValue>(result); }来源
是允许在操作中使用多种返回类型的原因.
Is what allows for the use of multiple return types in the action.
[HttpGet("test123")] public ActionResult<string> Test123() { if(someCondition) return "String value"; //<--String return Ok(); //<-- OkResult }返回字符串时,将调用 ActionResult< TValue>(TValue值)运算符,并返回有效的 ActionResult< TValue> ,反之亦然.
When the string is returned the ActionResult<TValue>(TValue value) operator is invoked, returning a valid ActionResult<TValue> and vice versa of the other operator.
更多推荐
ASP.NET Core如何将任何类型转换为ActionResult< T>.控制器动作的返回类型?
发布评论