首页 > 解决方案 > 无法转换任务> 到任务>

问题描述

我正在围绕 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<List<TEntity>>为没有错误。
有谁知道为什么它不能转换它?谢谢!

标签: c#asynchronousasync-awaitcovariancecontravariance

解决方案


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

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();
}

推荐阅读