ActionResult<IEnumerable<T>>必须返回一个 List<T> [英] ActionResult&lt;IEnumerable&lt;T&gt;&gt; has to return a List&lt;T&gt;

查看:29
本文介绍了ActionResult<IEnumerable<T>>必须返回一个 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 我可以只返回

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''Microsoft.AspNetCore.Mvc.ActionResult'

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 不能确定 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/en-us/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.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆