为什么 C# 4.0 的协变/逆变仅限于参数化接口和委托类型?
这是 CLR 的限制还是与现有代码存在兼容性问题?
这是否与 C# 4.0 中委托组合的混乱方差有关?
编辑: 是否有可能有一种使用协变/逆变的语言在 CLR 上运行而没有这种限制?
Is this a limitation of the CLR or are there compatibility concerns with existing code?
Is this related to the messed up variance of delegate combining in C# 4.0?
Edit:
Would it be possible to have a language using co-/contravariance without that limitation running on the CLR?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将需要阅读 Eric Lippert 的文章,了解它为何如此工作。缺点是他们允许尽可能多的差异,而不允许开发人员在编程中犯下可能导致难以追踪错误的严重错误。 4.0 中的差异量比 3.0 规则大大扩展,据我了解,这是对开发人员有利的内容和安全允许的内容之间的平衡,不会因无意的错误而造成太多麻烦。
链接
You are going to want to read Eric Lippert's post on why it works the way it does. The short of it is that they allowed as much variance as possible without allowing developers to make bad mistakes in programming that could cause difficult to track down errors. The amount of variance in 4.0 is greatly expanded over the 3.0 rules, and from what I understand it was a balance between what is benificial to the developer and what is safe to allow without causing too much of a headache through unintentional mistakes.
Link
简单的回答:这是 CLR 的限制。
(我还没有在任何地方看到对此有一个好的、具体的解释......我不记得在 Eric 的博客系列中看到过关于它的解释,尽管我很可能在某个地方错过了它。)
有一件事我想说的是,委托和接口都已经在实际类型上形成了“间接层”;如果您愿意的话,可以查看对方法或类的看法。从一种观点转变为另一种观点是相当合理的。对我来说,实际的类感觉像是一种更具体的表示——从一种具体表示转换到另一种感觉不太合理。但这是一个非常敏感的解释,而不是真正的技术限制。
Simple answer: it's a CLR limitation.
(I haven't seen a good, concrete explanation for this anywhere... I don't remember seeing one in Eric's blog series about it, although I may well have missed it somewhere.)
One thing I would say is that both delegates and interfaces already form "layers of indirection" over the real types; views on methods or classes, if you will. Changing from one view to another view is fairly reasonable. The actual class feels like a more concrete representation to me - and shifting from one concrete representation to another feels less reasonable. This is a very touchy-feely explanation rather than a genuine technical limitation though.
这是 CLR 的限制。请参阅 为什么 C# (4.0) 不允许泛型类类型中存在协变和逆变? 以获得更多评论。
It is a CLR limitation. See Why does C# (4.0) not allow co- and contravariance in generic class types? for additional commentary.