[英]Contravariance generic modifier in
public interface IOInitializable<in ItemType>
What does contravariant: converting from narrower (circle) to wider (Shapes) 什么是反变的:从较窄的(圆形)转换为较宽的(形状)
mean for an interface? 意味着接口?
What are the consequence and the dangers? 有什么后果和危险?
I've read http://msdn.microsoft.com/en-us/library/dd469484.aspx but this does not help me. 我已经阅读http://msdn.microsoft.com/zh-cn/library/dd469484.aspx,但这对我没有帮助。
I'd recommend reading this explaination from Tomas: 我建议阅读Tomas的以下解释:
The theory behind covariance and contravariance in C# 4
C#4中协方差和协方差背后的理论
It boils down to the fact that if you have a method call that is passing a number of "Circles", you can use a function that accepts a number of "Shapes" as long as it doesn't return a "Shape" (because that may or may not be a "Circle"). 归结为以下事实:如果您的方法调用传递了多个“圆”,则可以使用接受多个“形状”的函数,只要该函数不返回“形状”即可(因为可能是也可能不是“圆圈”)。
IComparer is a good example to demonstrate this. IComparer是一个很好的例子来证明这一点。 IComparer looks like this:
IComparer看起来像这样:
IComparer<in T>
Take the following: 采取以下措施:
IComparer<Primate>
IComparer<Chimpanzee>
where Chimpanzee : Primate
(of course). Chimpanzee : Primate
(当然)。 A method which requires an IComparer<Chimpanzee>
can take an IComparer<Primate>
as an argument, because if the comparer can compare primates, it can also compare chimpanzees, as it uses traits common to the two types to affect the comparison . 要求
IComparer<Chimpanzee>
可以将IComparer<Primate>
作为参数,因为如果比较器可以比较灵长类,它也可以比较黑猩猩,因为它使用两种类型共有的特征来影响比较 。
A good way to think of this is in terms of functionality. 考虑到这一点,一个好的方法就是功能。 Covariance allows more complex objects to be passed which implement a core functionality (like passing a string for an object).
协方差允许传递实现核心功能的更复杂的对象(例如,为对象传递字符串)。 Contravariance does something similar... comparing all primates is more complex than just comparing chimpanzees.
矛盾的变化类似...比较所有灵长类动物比仅比较黑猩猩要复杂得多。 It allows you to replace a comparer for a specific type with one which compares a more general type.
它使您可以用一种比较普通类型的比较器替换特定类型的比较器。 In this sense, the "in" applies more to the functionality of the method than the actual type passed.
在这种意义上,“ in”比传递的实际类型更多地应用于方法的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.