【问题标题】:Cannot convert Task<List<TEntity>> to Task<IList<TEntity>>无法将 Task<List<TEntity>> 转换为 Task<IList<TEntity>>
【发布时间】:2019-06-06 12:23:09
【问题描述】:

我正在围绕 EF Core DbSet 编写一个小型包装方法。我有以下方法:

public Task<IList<TEntity>> GetAsync(Func<IQueryable<TEntity>, IQueryable<TEntity>> getFunction)
{
    if (getFunction == null)
    {
        Task.FromResult(new List<TEntity>());
    }
    return getFunction(_dbSet).AsNoTracking().ToListAsync();
}

如您所见,该类是通用的,_dbSet 是上下文中具体DbSet 的一个实例。然而,这个问题并不重要。
对于代码,我收到以下错误:

[CS0029] 无法隐式转换类型 'System.Threading.Tasks.Task>' 到 'System.Threading.Tasks.Task>'

如果我将返回值更改为Task&lt;List&lt;TEntity&gt;&gt;,则没有错误。
有谁知道为什么它不能转换它?谢谢!

【问题讨论】:

  • @Sinatr 你可以提出修改建议,我很乐意接受 :) 还是谢谢你
  • Task 不是接口,因此doesn't support covarianceTask&lt;List&lt;...&gt;&gt; 只能产生 List&lt;...&gt; 而不是任何实现 IList&lt;...&gt; 的类。可以想象这样做会很有用,但被认为不足以实际实施。

标签: c# asynchronous async-await covariance contravariance


【解决方案1】:

我认为最简单的方法是等待任务。所以它会以最小的变化工作:

public async Task<IList<TEntity>> GetAsync(Func<IQueryable<TEntity>, IQueryable<TEntity>> 
getFunction)
{
    if (getFunction == null)
    {
        return new List<TEntity>();
    }
    return await getFunction(_dbSet).AsNoTracking().ToListAsync();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多