使用ASP.NET Core 2.1获取以下代码:
[HttpGet("/unresolved")]
public async Task<ActionResult<IEnumerable<UnresolvedIdentity>>> GetUnresolvedIdentities()
{
var results = await _identities.GetUnresolvedIdentities().ConfigureAwait(false);
return results.ToList();
}
Run Code Online (Sandbox Code Playgroud)
因为我本来以为GetUnresolvedIdentities()回报IEnumerable<UnresolvedIdentity>,我可以只返回
return await _identities.GetUnresolvedIdentities().ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)
除了我不能,因为我得到这个错误:
CS0029无法将类型隐式转换
'System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>'为'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>>'
我需要它.ToList(),这很烦人,因为它是2行而不是1行.
为什么无法ActionResult<T>弄清楚GetUnresolvedIdentities()返回IEnumerable<>并返回那个?
签名GetUnresolvedIdentities是:
Task<IEnumerable<UnresolvedIdentity>> GetUnresolvedIdentities();
Run Code Online (Sandbox Code Playgroud) 我在 ASP.NET Core 2.2 中的 WebApi 控制器中有一个简单的操作,如下所示:
[HttpGet("test123")]
public ActionResult<string> Test123()
{
return new OkResult();
}
Run Code Online (Sandbox Code Playgroud)
这编译得很好,但我想知道如何将OkResult对象转换为ActionResult<string>?
这些类有不同的继承链:
OkResult -> StatusCodeResult -> ActionResult
while ActionResult<TValue>only implementsIConvertToActionResult
换句话说,ActionResult<string>不是OkResult类的基类型。
如果我手动执行此操作并将代码更改为:
[HttpGet("test123")]
public ActionResult<string> Test123()
{
var a = new OkResult();
var b = a as ActionResult<string>; // Error CS0039
return b;
}
Run Code Online (Sandbox Code Playgroud)
代码不会编译转换错误:
错误 CS0039:无法通过引用转换、装箱转换、拆箱转换、包装转换或空类型转换将类型“Microsoft.AspNetCore.Mvc.OkResult”转换为“Microsoft.AspNetCore.Mvc.ActionResult”
第一个代码如何工作而第二个代码不起作用?如何从没有公共基类型的对象转换返回类型?