+-

我在ASP.NET Core 2.2中的WebApi控制器中有一个简单的操作,如下所示:
[HttpGet("test123")]
public ActionResult<string> Test123()
{
return new OkResult();
}
这样编译可以,但是我想知道OkResult对象怎么可能转换为ActionResult< string> ;? 这些类具有不同的继承链:
OkResult-> StatusCodeResult->动作结果
而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;
}
该代码将不会编译并显示转换错误:
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
第一个代码如何工作而第二个代码却不工作呢?如何从没有通用基本类型的对象转换返回类型?
最佳答案
来自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);
}
Source
是什么允许在操作中使用多种返回类型.
[HttpGet("test123")]
public ActionResult<string> Test123() {
if(someCondition) return "String value"; //<--String
return Ok(); //<-- OkResult
}
当返回字符串时,调用ActionResult< TValue>(TValue值)运算符,并返回有效的ActionResult< TValue>.反之亦然.
点击查看更多相关文章
转载注明原文:首页> C#> ASP.NET Core如何能够将任何类型转换为ActionResult返回类型的控制器操作? - 乐贴网