In .NET, the fact that IEnumerable<T>
extends IEnumerable
often comes in handy. Frustratingly, though IEqualityComparer<T>
and IComparer<T>
do not extend their non-generic counterparts, despite the fact that the EqualityComparer<T>
and Comparer<T>
classes implement both interfaces. Is there a reason for this discrepancy?
If I have a sequence of strings I can use that to get a sequence of objects, since each string is also an object. This is true of any sequence; I can always get a sequence of objects when given any sequence.
If I have an object that can compare two strings I can't use it to compare two objects, since those two objects might not be strings.
The reason for this is because IEnumerable<T>
is covariant, whereas IComparer
and IEqualityComparer
are not. (Not just in the C# sense, although that's true as well, but also in the conceptual computer science sense.)
As for why the concrete EqualityComparer<T>
and Comparer
classes implement both interfaces, rather than not just the generic versions, is a decision that can only really be explained by the employees who choose to create those types. I'd imagine that they did it because at the time enough people were using the non-generic versions of the interfaces that they wanted the types to be usable with all of the existing non-generic code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.