C# IComparer<T> standard usage question

假装没事ソ 提交于 2019-12-05 16:42:58

Yes, that would be the standard. Its explicitly stated for IComparable:

If A.CompareTo(B) returns zero and B.CompareTo(C) returns zero, then A.CompareTo(C) is required to return zero.

I can't find anything in the official documentation that comes right out and states the same thing for ICompare but I think its safe to assume the same holds true.

It has nothing to do with C#, it's a simple mathematical rule: Transitivity: http://en.wikipedia.org/wiki/Transitive_relation

So, yes in short.

--- Added information due to comment ---

If you go and read the documentation about IComparer: http://msdn.microsoft.com/en-us/library/system.collections.icomparer.compare.aspx

you'll see that:

Compares two objects and returns a value indicating whether one is less than, 
equal to, or greater than the other.

In other word, that means that when comparing object "a" and "b", you should always get the same result when calling multiple time the method Compare. If it's not the case, it means that you will get undefined behavior and it will be impossible to rely on that function for doing any sorting or comparison.

So, when you implement this method properly, the Transitivity rule apply and you can say without any doubt that a == c.

I hope that clarify your questioning about the implementation problem.

It is part of the interface contract that if a == b and b == c that a == c (transitive property of equality). This is not enforced anywhere in code, but it is required for it to function correctly.

Equality is transitive, so yes you should assume that, and develop your IComparer with that in mind.

Transitivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!