天天看點

IComparable類型排序接口

// 摘要: 

    //     定義一種特定于類型的通用比較方法,值類型或類通過實作此方法對其執行個體進行排序。

    [ComVisible(true)]

    public interface IComparable

    {

        // 摘要: 

        //     将目前執行個體與同一類型的另一個對象進行比較,并傳回一個整數,該整數訓示目前實

                //例在排序順序中的位置是位于另一個對象之前、之後還是與其位置相同。

        //

        // 參數: 

        //   obj:

        //     與此執行個體進行比較的對象。

        // 傳回結果: 

        //     一個值,訓示要比較的對象的相對順序。傳回值的含義如下:值含義小于零此執行個體小于             //obj。零此執行個體等于 obj。大于零此執行個體大于 obj。

        // 異常: 

        //   System.ArgumentException:

        //     obj 不具有與此執行個體相同的類型。

        int CompareTo(object obj);

    }

備注:

    此接口由具有可排序值的類型實作。 它要求實作類型定義單個方法 CompareTo(Object),該方法訓示目前執行個體在排序順序中的位置是位于同一類型的另一個對象之前、之後還是與其位置相同。 執行個體的 IComparable 實作由 Array.Sort 和 ArrayList.Sort 等方法自動調用。CompareTo(Object) 方法的實作必須傳回有三個值之一的 Int32,如下表中所示。

示例代碼:(來自官方開發文檔)

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 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);

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

若疑問可參看官方的開發者文檔!