C#的IComparer< T>标准的使用问题 [英] C# IComparer<T> standard usage question

查看:137
本文介绍了C#的IComparer< T>标准的使用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这是否是在C#中使用的IComparer标准的问题。说我有,其中有三个用户对象的情况:P1,P2和P3。说我叫传递P1和P2的比较方法,结果是0。这基本上意味着两个人应该被归类为相等。现在说我叫比较法传入P2和P3和的结果是0为好。同样,这意味着,两个人都相等。从逻辑上说,可以假设P1和P3也相等;然而,比较法可以实施然而有人决定来实现它。 ?因此,它是一个标准来实现它以这样一种方式,P1和P3也将在这种情况下返回0



这里是要问什么,我的代码:

  //假设这些都是正确初始化
的人P1 = NULL,P2 = NULL,P3 = NULL;
的IComparer<&人GT;比较器= NULL;

//比较的人1到人2和结果是0
Debug.Assert的(comparer.Compare(P1,P2)== 0);

//比较人2对人3和结果是0
Debug.Assert的(comparer.Compare(P2,P3)== 0);

//这会是一个公平的假设,即人1和3人也将是0?
Debug.Assert的(comparer.Compare(P1,P3)== 0);


解决方案

是的,这将是标准配置。它明确指出了IComparable的:




如果A.CompareTo(B)返回零和
B.CompareTo(C)返回零,那么
A.CompareTo(C)被要求返回
为零。




我找不到任何官方文件中附带的权利,并国ICompare同样的事情,但我认为它的安全承担同样如此。


I have a question with whether or not this is a standard for using IComparer in C#. Say I have a situation in which there are three Person objects: P1, P2, and P3. Say I call the Compare method passing in P1 and P2 and the result is 0. This essentially means the two people should be categorized as equal. Now say I call the Compare method passing in P2 and P3 and the result for that is 0 as well. Again, this means the two people are equal. Logically speaking, one can assume P1 and P3 are equal as well; however, the Compare method could be implemented however someone decides to implement it. So is it a standard to implement it in such a way that P1 and P3 would also return 0 in this case?

Here's code of what I'm asking:

// Assume these are initialized properly
Person p1 = null, p2 = null, p3 = null;
IComparer<Person> comparer = null;

// Compare person 1 to person 2 and result is 0
Debug.Assert(comparer.Compare(p1, p2) == 0);

// Compare person 2 to person 3 and result is 0
Debug.Assert(comparer.Compare(p2, p3) == 0);

// Would this be a fair assumption that person 1 and person 3 would also be 0?
Debug.Assert(comparer.Compare(p1, p3) == 0);

解决方案

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.

这篇关于C#的IComparer&LT; T&GT;标准的使用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆