2013-07-19 34 views
0
public static void sort(IComparable[] a) 
{ 
    int N = a.Length; 
    for (int i = 0; i < N; i++) 
    { 
     for (int j = i; j > 0 && less(a[j], a[j - 1]); j--) 
     { 
      exch(a, j, j - 1); 
     } 
     isSorted(a, 0, i); 
    } 
    isSorted(a); 
} 

以上就是簡單的排序代碼,我在本書中,代碼是用Java寫的,我嘗試在C#中翻譯。 一切都很好,除了如何傳遞參數。 的Int32是落實icamparable,但我怎麼可以創建一個IComparable[]實例,並傳遞給排序功能。如何在c#中創建IComparable []?

IComparable[] b = new int[] { 2, 3, 3, 3, 3, 3, 3, 3 }; 

不起作用。

回答

5

如果你想初始化IComparable與數組int你需要創建副本。寫代碼最簡單的方法是使用LINQ的CastToArray

IComparable[] b = (new int[] { 2, 3, 3, 3, 3, 3, 3, 3 }) 
    .Cast<IComparable>().ToArray(); 

注:通常你會使用泛型來寫這個方法 - 像

public static void Sort<T>(T[] a) where T: IComparable<T>