IEnumerable<T>
在 .NET 中,扩展的事实IEnumerable
经常派上用场。令人沮丧的是,尽管and类实现了这两个接口,但IEqualityComparer<T>
并IComparer<T>
没有扩展它们的非泛型对应物。这种差异有原因吗?EqualityComparer<T>
Comparer<T>
1 回答
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.