【发布时间】: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