[英]Returning IEnumerable Implementation from within Task
I can do: 我可以:
public static IEnumerable<string> Do()
{
return new List<string>();
}
But if I'm returning a Task, I'm not allowed to do the same thing: 但是,如果我要返回任务,则不允许做同样的事情:
public static Task<IEnumerable<string>> DoTask()
{
return Task.Factory.StartNew(() =>
{
return new List<string>(); //no no
});
}
I'm implementing a async repository in .NET 4.0 and ran across this. 我正在.NET 4.0中实现一个异步存储库,并在此运行。 I was just curious why the compiler can't cast my
List
down when wrapped in a Task? 我只是很好奇为什么编译器包裹在Task中时为什么不能将我的
List
下来? Of course, my work around is just throwing AsEnumerable
on it , but I wonder why this limitation exists? 当然,我的工作只是在上面抛出
AsEnumerable
,但是我想知道为什么存在此限制?
Converting from Task<List<string>>
to Task<IEnumerable<string>>
require Task<T>
to be covariant AND inner types to be interfaces. 从
Task<List<string>>
为Task<IEnumerable<string>>
要求Task<T>
是协变的,而内部类型是接口。 Neither is true in this case, so conversion not allowed. 在这种情况下都不正确,因此不允许进行转换。
Obvious fix - to cast result of Task
to necessary type either by explicitly specifying type for lambda 明显的修正-通过为lambda明确指定类型,将
Task
结果转换为必要的类型
return Task.Factory.StartNew((Func<IEnumerable<string>>)
(() =>
{
return new List<string>();
}));
or implicitly by casting result: 或通过强制转换结果隐式:
return (IEnumerable<string>)new List<string>();
Detailed information - Covariance and Contravariance FAQ 详细信息- 协方差和协方差常见问题
Why Task<List<string>>
is result of TaskFactory.StartNew call: 为什么
Task<List<string>>
是TaskFactory.StartNew调用的结果:
Lambda passed to the StartNew
call does not explicitly specify its type so compiler infers its return type from return
statement. 传递给
StartNew
调用的Lambda没有显式指定其类型,因此编译器从return
语句推断其返回类型。 Since return
clearly states new List...
overall type of lambda is equivalent in this case to Func<List<string>>
. 由于
return
明确指出了new List...
在这种情况下,lambda的总体类型等效于Func<List<string>>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.