实现IComparable接口,需要实现CompareTo方法,该方法在MSDN中定义如下:
Compares the current instance with another object of the same type.
(比较当前实例和另一个相同类型的对象)
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Parameters
-
obj
-
An object to compare with this instance.
Return Value
A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings:| Value | Meaning |
|---|---|
| Less than zero | This instance is less than obj. 若返回值为负,当前实例小于比较对象 |
| Zero | This instance is equal to obj. 若返回值为零,当前实例等于比较对象 |
| Greater than zero | This instance is greater than obj. 若返回值为正,当前实例大于比较对象 |
实际应用中,System.Array中的很多方法都需要实现该接口,如:
- Array.IndexOf
- Array.LastIndexOf
- Array.Sort
- Array.Reverse
- Array.BinarySearch
示例代码如下:
using
System;2

3
namespace
icom_ex4

{5
public class XClass : IComparable 6

{7
public XClass(int data)8

{9
propNumber = data;10
}11

12
private int propNumber;13

14
public int Number15

{16
get 17

{18
return propNumber;19
}20
}21

22
public int CompareTo(object obj)23

{24
XClass comp = (XClass)obj;25
if (this.Number == comp.Number)26
return 0;27
if (this.Number < comp.Number)28
return -1;29
return 1;30
}31
32
}33
public class Starter34

{35
public static void Main()36

{37

XClass[] objs =
{ new XClass(5), new XClass(10) ,new XClass(1)};38
Array.Sort(objs);39
foreach (XClass obj in objs)40
Console.WriteLine(obj.Number);41
}42
}43
}
44
本文详细介绍了如何通过实现IComparable接口中的CompareTo方法来定义对象之间的比较规则。文章提供了具体的C#示例代码,并展示了该接口在数组排序等功能中的应用。
171

被折叠的 条评论
为什么被折叠?



