问题描述
有人可以告诉我为什么它不起作用吗?
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:
但在其正下方,我有此方法:
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);
这篇关于使用异步编程进行类型转换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!