ActionResult< IEnumerable< T>必须返回List< T>. [英] ActionResult<IEnumerable<T>> has to return a List<T>
问题描述
使用ASP.NET Core 2.1进行以下代码:
Take the following code using ASP.NET Core 2.1:
[HttpGet("/unresolved")]
public async Task<ActionResult<IEnumerable<UnresolvedIdentity>>> GetUnresolvedIdentities()
{
var results = await _identities.GetUnresolvedIdentities().ConfigureAwait(false);
return results.ToList();
}
自GetUnresolvedIdentities()
返回IEnumerable<UnresolvedIdentity>
以来,我一直以为我可以返回
I would have thought since GetUnresolvedIdentities()
returns IEnumerable<UnresolvedIdentity>
that I could just return
return await _identities.GetUnresolvedIdentities().ConfigureAwait(false);
除了我不能,因为出现此错误:
Except I can't, as I get this error:
CS0029无法隐式转换类型
'System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>'
到'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>>'
CS0029 Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>'
to'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>>'
我需要.ToList()
,这很烦人,因为它是2行而不是1行.
I need the .ToList()
, which is annoying as it's 2 lines rather than 1.
为什么ActionResult<T>
不能弄清楚GetUnresolvedIdentities()
返回一个IEnumerable<>
而仅仅返回它呢?
Why can't ActionResult<T>
figure out that GetUnresolvedIdentities()
returns an IEnumerable<>
and just return that?
GetUnresolvedIdentities
的签名是:
Task<IEnumerable<UnresolvedIdentity>> GetUnresolvedIdentities();
推荐答案
从msdn中获取此文档: https ://docs.microsoft.com/zh-cn/aspnet/core/web-api/action-return-types?view = aspnetcore-2.1#actionresultt-type
Take this documentation from msdn: https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.1#actionresultt-type
C#不支持接口上的隐式强制转换运算符. 因此,将接口转换为具体类型是 必须使用
ActionResult<T>
.
C# doesn't support implicit cast operators on interfaces. Consequently, conversion of the interface to a concrete type is necessary to use
ActionResult<T>
.
这篇关于ActionResult< IEnumerable< T>必须返回List< T>.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!