如何实现IComparable以对自定义类型的数组进行排序?

时间:2014-07-04 21:17:07

标签: c# arrays sorting icomparable

我为我的C#类编写了一个程序,需要弄清楚如何实现IComparable以便能够对自定义类型的数组进行排序。它编译时没有错误,但在运行时抛出异常:

  

System.InvalidOperationException:无法比较数组中的两个元素。 ---> System.ArgumentException:至少有一个对象必须实现IComparable。

我已经搜索了几个小时才找到无效的解决方案。关于这个问题有很多信息,但我可能只是在思考它。我将发布该计划,如果有人能指出我正确的方向并给出解释,我将永远感激,因为截止日期即将来临。
附:这是我第一次在这里发帖,所以在批评我的缺点时要温柔一点。

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

2 个答案:

答案 0 :(得分:3)

异常信息非常清楚。

must implement IComparable

这意味着您必须为IComparable课程实施Player

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

答案 1 :(得分: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);
相关问题