为什么任务< T>不共变体? [英] Why is Task<T> not co-variant?
问题描述
class ResultBase {}
class Result : ResultBase {}
Task<ResultBase> GetResult() {
return Task.FromResult(new Result());
}
编译器告诉我,它不能隐式转换任务< ;结果>
到任务< ResultBase>
。有人能解释这是为什么?我本来期望协方差,让我写这样的代码。
The compiler tells me that it cannot implicitly convert Task<Result>
to Task<ResultBase>
. Can someone explain why this is? I would have expected co-variance to enable me to write the code in this way.
推荐答案
据的人谁可能是在知道 ...
的理由是协方差的好处是$抵销b $ b杂乱的缺点(即每个人都必须做出是否要在他们的代码中的每一个
座使用任务或ITask一个
号决定)。
The justification is that the advantage of covariance is outweighed by the disadvantage of clutter (i.e. everyone would have to make a decision about whether to use Task or ITask in every single place in their code).
这听起来好像还没有一个非常引人注目的动机无论哪种方式。 ITask<出T>
将需要大量新的过载,可能相当引擎盖下一个位(我不能证明如何实际基类中实现或如何特别是相比天真的实现),但更多的方式在这些形式 LINQ
式的扩展方法。
It sounds to me like there is not a very compelling motivation either way. ITask<out T>
would require a lot of new overloads, probably quite a bit under the hood (I cannot attest to how the actual base class is implemented or how special it is compared to a naive implementation) but way more in the form of these linq
-like extension methods.
某些别有用心的人取得了良好的一点 - 最好将时间花在类
ES协变和逆变。我不知道有多难那会,但是这听起来像一个更好地利用时间给我。
Somebody else made a good point - the time would be better spent making class
es covariant and contravariant. I don't know how hard that would be, but that sounds like a better use of time to me.
在另一方面,有人指出,这将是非常酷有一个真正的收益回报率
像功能可在异步
方法。我的意思是,没有戏法。
On the other hand, somebody mentioned that it would be very cool to have a real yield return
like feature available in an async
method. I mean, without sleight of hand.
这篇关于为什么任务< T>不共变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!