// 摘要:
// 定義一種特定于類型的通用比較方法,值類型或類通過實(shí)現(xiàn)此方法對其實(shí)例進(jìn)行排序。
[ComVisible(true)]
public interface IComparable
{
// 摘要:
// 將當(dāng)前實(shí)例與同一類型的另一個對象進(jìn)行比較,并返回一個整數(shù),該整數(shù)指示當(dāng)前實(shí)
//例在排序順序中的位置是位于另一個對象之前、之后還是與其位置相同。
//
// 參數(shù):
// obj:
// 與此實(shí)例進(jìn)行比較的對象。
//
// 返回結(jié)果:
// 一個值,指示要比較的對象的相對順序。返回值的含義如下:值含義小于零此實(shí)例小于 //obj。零此實(shí)例等于 obj。大于零此實(shí)例大于 obj。
//
// 異常:
// System.ArgumentException:
// obj 不具有與此實(shí)例相同的類型。
int CompareTo(object obj);
}
備注:
此接口由具有可排序值的類型實(shí)現(xiàn)。 它要求實(shí)現(xiàn)類型定義單個方法 CompareTo(Object),該方法指示當(dāng)前實(shí)例在排序順序中的位置是位于同一類型的另一個對象之前、之后還是與其位置相同。 實(shí)例的 IComparable 實(shí)現(xiàn)由 Array.Sort 和 ArrayList.Sort 等方法自動調(diào)用。CompareTo(Object) 方法的實(shí)現(xiàn)必須返回有三個值之一的 Int32,如下表中所示。
示例代碼:(來自官方開發(fā)文檔)
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
若疑問可參看官方的開發(fā)者文檔!
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動態(tài)BGP最優(yōu)骨干路由自動選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動現(xiàn)已開啟,新人活動云服務(wù)器買多久送多久。
當(dāng)前題目:IComparable類型排序接口-創(chuàng)新互聯(lián)
路徑分享:http://chinadenli.net/article34/epcse.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、用戶體驗(yàn)、全網(wǎng)營銷推廣、標(biāo)簽優(yōu)化、品牌網(wǎng)站建設(shè)、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容