我爲我的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);
}
}
}
'Player'需要實現'IComparable'。不知道問題是什麼。標題中問題的答案是:您實現了IComparable。 –
爲了解決您的問題,您需要爲Player類實現IComparable。爲此,您需要知道您最初想如何排序玩家。例如。您可以按姓名首字母或分數排序。 – grzkv