using System;
using System.Collections;
public class Temperature : IComparable
{
// The temperature value
protected double temperatureF;
public int CompareTo(object obj) {
Temperature otherTemperature = obj as Temperature;
if (otherTemperature != null)
return this.temperatureF.CompareTo(otherTemperature.temperatureF);
else
throw new ArgumentException("Object is not a Temperature");
}
public double Fahrenheit
{
get
{
return this.temperatureF;
}
set {
this.temperatureF = value;
}
}
public double Celsius
{
get
{
return (this.temperatureF - 32) * (5.0/9);
}
set
{
this.temperatureF = (value * 9.0/5) + 32;
}
}
}
public class CompareTemperatures
{
public static void Main()
{
ArrayList temperatures = new ArrayList();
// Initialize random number generator.
Random rnd = new Random();
// Generate 10 temperatures between 0 and 100 randomly.
for (int ctr = 1; ctr <= 10; ctr++)
{
int degrees = rnd.Next(0, 100);
Temperature temp = new Temperature();
temp.Fahrenheit = degrees;
temperatures.Add(temp);
}
// Sort ArrayList.
temperatures.Sort();
foreach (Temperature temp in temperatures)
Console.WriteLine(temp.Fahrenheit);
}
}这是我从MSDN中得到的一个例子。在上面的示例中,在数组列表的排序函数()中使用了this.TemperatureF.CompareTo(otherTemperature.temperatureF),所以比较是如何完成的。谁为比较提供了另一个引用对象(This)?
发布于 2011-03-11 17:19:09
这取决于使用IComparable的情况,但在对列表进行排序的示例中,其他引用是要与之进行比较的列表中的其他项。与列表中的哪些对象进行比较将取决于排序算法。
而且,与普通的IComparable相比,我更喜欢通用的IComparable<T>。
发布于 2011-03-11 17:19:10
"compareTo“用于比较如下两个对象: this.compareTo(anOtherObject)
所以,这是第一个对象,第二个是anOtherObject。
要对数组进行排序,框架调用此方法将当前对象( this )与下一个对象进行比较。
发布于 2011-03-11 17:21:42
CompareTo(object other)将通过实现所使用的排序算法来调用。在您的例子中,是ArrayList.Sort()使用的排序算法。Sort()
other是ArrayList中的一项。
查看您获得示例的文章中的Remarks部分
https://stackoverflow.com/questions/5270927
复制相似问题