博客园  :: 首页  :: 联系 :: 管理

IComparable 泛型接口

Posted on 2008-08-01 10:18  sunrack  阅读(563)  评论(0编辑  收藏  举报
IComparable 泛型接口

注意:此接口在 .NET Framework 2.0 版中是新增的。

定义由值类型或类实现的通用的比较方法,以为排序实例创建类型特定的比较方法。

命名空间:System
程序集:mscorlib(在 mscorlib.dll 中)

C#
public interface IComparable<T>

此接口由值可以排序的类型实现;例如数值或字符串类。值类型或类实现 CompareTo 方法以创建适合排序等目的的类型特定的比较方法。

Note注意

IComparable 接口定义 CompareTo 方法,该方法确定实现类型的实例的排序顺序。IEquatable 接口定义 Equals 方法,该方法确定实现类型的实例的相等性。

给实现者的说明 用实现此接口的类型替换 IComparable 接口的类型参数。

下面的代码示例演示一个简单的 Temperature 对象的 IComparable 实现。该示例创建带有 Temperature 对象键的字符串的 SortedList 集合,并将多个温度和字符串对添加到无序列表中。SortedList 集合使用 IComparable 实现对列表项进行排序,然后,这些列表项将按温度的升序显示。

using System;
using System.Collections.Generic;
public class Temperature : IComparable<Temperature>
{
// Implement the CompareTo method. For the parameter type, Use 
// the type specified for the type parameter of the generic 
// IComparable interface. 
//
public int CompareTo(Temperature other)
{
// The temperature comparison depends on the comparison of the
// the underlying Double values. Because the CompareTo method is
// strongly typed, it is not necessary to test for the correct
// object type.
return m_value.CompareTo(other.m_value);
}
// The underlying temperature value.
protected double m_value = 0.0;
public double Celsius
{
get
{
return m_value - 273.15;
}
}
public double Kelvin
{
get
{
return m_value;
}
set
{
if (value < 0.0)
{
throw new ArgumentException("Temperature cannot be less than absolute zero.");
}
else
{
m_value = value;
}
}
}
public Temperature(double degreesKelvin)
{
this.Kelvin = degreesKelvin;
}
}
public class Example
{
public static void Main()
{
SortedList<Temperature, string> temps =
new SortedList<Temperature, string>();
// Add entries to the sorted list, out of order.
temps.Add(new Temperature(2017.15), "Boiling point of Lead");
temps.Add(new Temperature(0), "Absolute zero");
temps.Add(new Temperature(273.15), "Freezing point of water");
temps.Add(new Temperature(5100.15), "Boiling point of Carbon");
temps.Add(new Temperature(373.15), "Boiling point of water");
temps.Add(new Temperature(600.65), "Melting point of Lead");
foreach( KeyValuePair<Temperature, string> kvp in temps )
{
Console.WriteLine("{0} is {1} degrees Celsius.", kvp.Value, kvp.Key.Celsius);
}
}
}
/* This code example produces the following output:
Absolute zero is -273.15 degrees Celsius.
Freezing point of water is 0 degrees Celsius.
Boiling point of water is 100 degrees Celsius.
Melting point of Lead is 327.5 degrees Celsius.
Boiling point of Lead is 1744 degrees Celsius.
Boiling point of Carbon is 4827 degrees Celsius.
*/

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求