关于IComparable接口

本文详细介绍了如何通过实现IComparable接口中的CompareTo方法来定义对象之间的比较规则。文章提供了具体的C#示例代码,并展示了该接口在数组排序等功能中的应用。

实现IComparable接口,需要实现CompareTo方法,该方法在MSDN中定义如下:

 

Compares the current instance with another object of the same type.

(比较当前实例和另一个相同类型的对象)

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

C#
int CompareTo (
            Object obj
            )

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

示例代码如下:

 

 1 using  System;
 2
 3 namespace  icom_ex
 4 ExpandedBlockStart.gifContractedBlock.gif {
 5    public class XClass : IComparable 
 6ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 7        public XClass(int data)
 8ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 9            propNumber = data;
10        }

11
12        private int propNumber;
13
14        public int Number
15ExpandedSubBlockStart.gifContractedSubBlock.gif        {
16            get 
17ExpandedSubBlockStart.gifContractedSubBlock.gif            {
18                return propNumber;
19            }

20        }

21
22        public int CompareTo(object obj)
23ExpandedSubBlockStart.gifContractedSubBlock.gif        {
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 Starter
34ExpandedSubBlockStart.gifContractedSubBlock.gif    {
35        public static void Main()
36ExpandedSubBlockStart.gifContractedSubBlock.gif        {
37ExpandedSubBlockStart.gifContractedSubBlock.gif            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
如不实现CompareTo函数,调用Array.Sort时会出现一个错误!

转载于:https://www.cnblogs.com/haoxin_li/archive/2008/08/29/1279528.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值