C#学习笔记 IComparable接口 IComparable<T>接口 IComparer接口

来源:互联网 发布:类似于易企秀的软件 编辑:程序博客网 时间:2024/05/22 14:25

ArrayList中有一个Sort()方法,它可以实现对集合的排序。但是集合中的类型必须要实现IComparable接口,因为排序需要类型的比较方法CompareTo(),参数为该类型的一个对象。

所以我们自己写的一个类,想要使用这个Sort()方法,必须实现这个IComparable()接口。CompareTo()方法的返回值是int类型的,如果大于1,就说明前者比后者大,如果为0,说明两者相等,如果小于0,说明后者大。

这个实现方法,改变了类本身。

using System;using System.Collections;namespace Simple{public class MainEntryPoint{static int Main(string[] args){ArrayList temps = new ArrayList();Random rm = new Random();for(int i = 0; i < 10; i++){double x = rm.Next(0,100);Temperature y = new Temperature();y.Fahrenheit = x;temps.Add(y);}temps.Sort();foreach(Temperature i in temps){Console.WriteLine(i.Fahrenheit);}return 0;}}public class Temperature : IComparable{private double temp;public int CompareTo(object obj){if(obj == null)return 1;Temperature value = obj as Temperature;if(value != null)return this.temp.CompareTo(value.Fahrenheit);throw new ArgumentException("Object is not a Temperature.");}public double Fahrenheit{get{return temp;}set{temp = value;}}public double Celsius{get{return (temp - 32) * (5.0 / 9);}set{temp = (value * 9.0 / 5) + 32;}}}}

下面这个例子是使用了IComparable<T>,因为我还没有学习到集合,我从代码中看到的,大概就是SortedList<Temperature, string>这个是一个有排序功能的一个集合类,然后放的是map这种类型的数据,根据key来排序。但是我做的这个例子是key是一个类,然后得对> < >= <=这四个符号重载,实现自定义类的排序。

using System;using System.Collections.Generic;namespace Simple{public class MainEntryPoint{static int Main(string[] args){SortedList<Temperature, string> list  = new SortedList<Temperature, string>();list.Add(new Temperature(2017.15), "Boiling point of Lead");list.Add(new Temperature(0), "Absolute zero");list.Add(new Temperature(273.15), "Freezing point of water");list.Add(new Temperature(5100.15), "Boiling point of Carbon");list.Add(new Temperature(373.15), "Boiling point of water");list.Add(new Temperature(600.65), "Melting point of Lead");foreach(KeyValuePair<Temperature, string> i in list){Console.WriteLine("{0} is {1} degrees Celsius.", i.Value, i.Key.Celsius);}return 0;}}public class Temperature : IComparable<Temperature>{public int CompareTo(Temperature other){if(other == null)return 1;return temp.CompareTo(other.Temp);}public static bool operator >(Temperature t1, Temperature t2){return t1.CompareTo(t2) == 1;}public static bool operator <(Temperature t1, Temperature t2){return t1.CompareTo(t2) == -1;}public static bool operator >=(Temperature t1, Temperature t2){return t1.CompareTo(t2) >= 0;}public static bool operator <=(Temperature t1, Temperature t2){return t1.CompareTo(t2) <= 0;}private double temp;public Temperature(double value){this.temp = value;}public double Temp{get{return temp;}set{if(value < 0.0)throw new ArgumentException("Temperature cannot be less than absolute zero.");temp = value;}} public double Celsius{get    {    return temp - 273.15;        }    }}}

如果想要不改变类,还想自定义比较方法就可以实现一个IComparer接口,实现Compare()方法,当腰使用排序时,Sort()方法中传入一个参数,这个参数是实现了IComparer接口的类实例,就可以实现排序了。

using System;using System.Collections;namespace Simple{public class MainEntryPoint{static int Main(string[] args){ArrayList list = new ArrayList();list.Add( "The" );    list.Add( "quick" );list.Add( "brown" );    list.Add( "fox" );    list.Add( "jumps" );    list.Add( "over" );list.Add( "the" );list.Add( "lazy" );list.Add( "dog" );Console.WriteLine("init:");PrintIndexAndValue(list);list.Sort();Console.WriteLine("default:");PrintIndexAndValue(list);Console.WriteLine("myReverserClass:");ReverserClass my = new ReverserClass();list.Sort(my);PrintIndexAndValue(list);return 0;}public static void PrintIndexAndValue(IEnumerable list){int i = 0;foreach(object obj in list){Console.WriteLine("\t[{0}]:{1}",i++,obj);}Console.WriteLine();}}public class ReverserClass : IComparer{int IComparer.Compare(object x, object y){return (new CaseInsensitiveComparer()).Compare(y, x);}}}



0 0
原创粉丝点击