2014-07-04 32 views
-3

我爲我的C#類編寫了一個程序,需要弄清楚如何實現IComparable以便能夠對自定義類型的數組進行排序。它編譯沒有錯誤,但在運行時拋出異常:如何實現IComparable來對自定義類型的數組進行排序?

System.InvalidOperationException:無法比較數組中的兩個元素。 ---> System.ArgumentException:至少有一個對象必須實現IComparable。

我搜索了幾個小時找到解決方案無濟於事。關於這個問題有很多信息,但我可能只是在推翻它。我會發布該計劃,如果有人能夠用正確的方向指出我的解釋,我會永遠感激,因爲截止日期很快就會到來。
P.S.這是我第一次在這裏發表,所以在批評我的缺點時請保持溫柔。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace HighScores4 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     {   
     string playerInitials; 
     int playerScore; 

     const int NUM_PLAYERS = 10; 

     Player[] stats = new Player[NUM_PLAYERS];   

     for (int index = 0; index < NUM_PLAYERS; index++) 
     { 
      Console.WriteLine("Please enter your initials: "); 
      playerInitials = Convert.ToString(Console.ReadLine()); 

      Console.WriteLine("Please enter your score: "); 
      playerScore = Convert.ToInt32(Console.ReadLine()); 

      stats[index] = new Player(playerScore, playerInitials);    
     } 

     Array.Sort(stats); **// Exception thrown here** 
     Array.Reverse(stats); 

     for (int index = 0; index < NUM_PLAYERS; index++) 
     { 
      Console.WriteLine(stats[index].ToString()); 
     } 

#if DEBUG 
     Console.ReadKey(); 
#endif 

     } 
    } 

    public class Player 
    {  
     public string Initials { get; set; } 
     public int Score { get; set; } 

     public Player(int score, string initials) 
     { 
     Initials = initials; 
     Score = Score; 
     } 

     public override string ToString() 
     { 
     return string.Format("{0, 3}, {1, 7}", Score, Initials); 
     } 
    } 
} 
+1

'Player'需要實現'IComparable'。不知道問題是什麼。標題中問題的答案是:您實現了IComparable。 –

+0

爲了解決您的問題,您需要爲Player類實現IComparable。爲此,您需要知道您最初想如何排序玩家。例如。您可以按姓名首字母或分數排序。 – grzkv

回答

2

異常消息非常清楚。

must implement IComparable 

這意味着你必須實現IComparablePlayer類。

public class Player : IComparable<Player> 
{ 
    ... 
} 
+0

感謝您的快速響應。我想我應該提到我需要按照分數對數組進行排序,並保持首字母與它們同步。 – user3806529

+1

他應該實施'IComparable ',而不是'IComparable'。 **另外:**或者,他可以使用'Array.Sort'的另一個重載,它需要一個額外的參數來指定如何比較玩家。 –

+0

它將如何被插入到構造函數體中? – user3806529

1

您可以使用lambda表達式創建IComparer<Player>(與Comparer<Type>.Create),並通過它Array.Sort(array, comparer)說法。代碼片段:

Comparer<Player> scoreComparer = 
    Comparer<Player>.Create((first, second) => first.Score.CompareTo(second.Score)); 

Array.Sort(tab, scoreComparer); 
相關問題