# IComparable.CompareTo 方法

2013/12/13

Namespace:  System

## 语法

```int CompareTo(
Object obj
)
```

obj

## 例外

ArgumentException

obj 不具有与此实例相同的类型。

## 备注

CompareTo 方法由具有可排序值的类型实现。它由非泛型集合对象（如 Sort）的方法自动调用来对数组中的每个成员进行排序。如果自定义类或结构未实现 IComparable，则其成员将无法排序，并且排序操作会引发 InvalidOperationException

A.CompareTo(A) 必须返回零。

## 示例

```
using System;
using System.Collections;

public class Temperature : IComparable
{
// The temperature value
protected double temperatureF;

public int CompareTo(object obj)
{
if (obj == null) return 1;

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 Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
Temperature[] temperatures = new Temperature[10];
// 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[ctr - 1] = temp;
}

// Sort ArrayList.
Array.Sort(temperatures);

foreach (Temperature temp in temperatures)
outputBlock.Text += temp.Fahrenheit + "\n";

}
}
// The example displays the following output (individual
// values may vary because they are randomly generated):
//       2
//       7
//       16
//       17
//       31
//       37
//       58
//       66
//       72
//       95

```

Windows Phone