使用异步编程进行类型转换错误 [英] Type conversion error with async programming

查看:65
本文介绍了使用异步编程进行类型转换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我为什么它不起作用吗?

Can anyone tell me why this is not working?

我有一个看起来像这样的方法:

I have a method that looks like this:

public virtual async Task<IList<User>> GetAll()
{
    return this.db.Users.Where(model => model.CompanyId.Equals(this.companyId, StringComparison.OrdinalIgnoreCase)).ToListAsync();
}

当我尝试编译代码时,出现错误提示:

when I try to compile my code I get an error stating:


错误10无法将类型'System.Threading.Tasks.Task>'隐式转换为'System.Collections.Generic.IList'。存在显式转换(是否缺少强制转换?)C:\Users\Jaymie\Documents\GitHub\Skipstone\Skipstone.Web\Repositories\UserRepository.cs 70 20 Skipstone.Web

Error 10 Cannot implicitly convert type 'System.Threading.Tasks.Task>' to 'System.Collections.Generic.IList'. An explicit conversion exists (are you missing a cast?) C:\Users\Jaymie\Documents\GitHub\Skipstone\Skipstone.Web\Repositories\UserRepository.cs 70 20 Skipstone.Web

但在其正下方,我有此方法:

Yet directly under it I have this method:

public Task<User> FindByIdAsync(string userId)
{
    return this.db.Users.Where(model => model.Id.Equals(userId, StringComparison.OrdinalIgnoreCase)).SingleOrDefaultAsync();
}

效果很好。

我认为我看不到树木的木头,所以需要别人的眼睛来帮助我:)

I think I can't see the wood for the trees so need someone else's eyes to help me out :)

推荐答案

ToListAsync 方法返回 Task< List< T>> 对象,该对象转换为 Task< List< User>> 对象,但方法的返回类型为 Task< IList< User>>

The ToListAsync methods return a Task<List<T>> object, which translate to a Task<List<User>> object in your case, but your method's return type is Task<IList<User>>.

此处的问题是 Task< T>中的 T 不支持协方差。

The issue here is that covariance is not supported for T in Task<T>.

因此,您可以将方法的返回类型更改为 Task< List< User>> ,或者您自己编写代码来进行转换:

So, either you change the method's return type to Task<List<User>>, or you write the code to make the conversion yourself:

return this.db.Users
    .Where(model => model.Id.Equals(userId, StringComparison.OrdinalIgnoreCase))
    .ToListAsync()
    .ContinueWith<IList<User>>(t => t.Result, TaskContinuationOptions.ExecuteSynchronously);

这篇关于使用异步编程进行类型转换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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