【问题标题】:How do you implement IComparable to sort an array of a custom type?您如何实现 IComparable 以对自定义类型的数组进行排序?
【发布时间】:2014-08-26 04:16:40
【问题描述】:

我为我的 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);
      } 
   } 
} 

【问题讨论】:

  • Player 需要实现IComparable。不知道问题是什么。标题中问题的答案是:你实现了 IComparable。
  • 为了使您的解决方案正常工作,您需要为 Player 类实现 IComparable。为此,您首先需要知道如何对玩家进行排序。例如。您可以按首字母或分数排序。

标签: c# arrays sorting icomparable


【解决方案1】:

异常信息非常清楚。

must implement IComparable

这意味着你必须为你的Player 类实现IComparable

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

【讨论】:

  • 感谢您的快速响应。我想我应该提到我需要按分数对数组进行排序,保持首字母与它们同步。
  • 他应该实现IComparable&lt;Player&gt;,而不是IComparable补充: 或者,他可以使用Array.Sort 的另一个重载,它接受一个额外的参数来指定如何比较玩家。
  • 如何将其插入到构造函数的主体中?
【解决方案2】:

您可以使用 lambda 表达式创建 IComparer&lt;Player&gt;(使用 Comparer&lt;Type&gt;.Create)并将其传递给 Array.Sort(array, comparer) 参数。代码sn-p:

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

Array.Sort(tab, scoreComparer);

【讨论】:

    猜你喜欢
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2022-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多