至少有一个对象必须实现IComparable

using System; using System.Xml; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { SortedSet PlayerList = new SortedSet(); while (true) { string Input; Console.WriteLine("What would you like to do?"); Console.WriteLine("1. Create new player and score."); Console.WriteLine("2. Display Highscores."); Console.WriteLine("3. Write out to XML file."); Console.Write("Input Number: "); Input = Console.ReadLine(); if (Input == "1") { Player player = new Player(); string PlayerName; string Score; Console.WriteLine(); Console.WriteLine("-=CREATE NEW PLAYER=-"); Console.Write("Player name: "); PlayerName = Console.ReadLine(); Console.Write("Player score: "); Score = Console.ReadLine(); player.Name = PlayerName; player.Score = Convert.ToInt32(Score); //==================================== //ERROR OCCURS HERE //==================================== PlayerList.Add(player); Console.WriteLine("Player \"" + player.Name + "\" with the score of \"" + player.Score + "\" has been created successfully!" ); Console.WriteLine(); } else { Console.WriteLine("INVALID INPUT"); } } } } } 

所以我一直得到“

至少有一个对象必须实现IComparable。

“当试图添加第二个玩家时,第一个玩家会工作,但第二个玩家不会。我也必须使用SortedSet因为这是工作的要求,这是学校的工作。

好吧,你正在尝试使用SortedSet<> …这意味着你关心订购。 但是通过它的声音你的Player类型没有实现IComparable 。 那么你期望看到什么样的订单?

基本上,您需要告诉您的Player代码如何比较一个玩家与另一个玩家。 或者,您可以在其他地方实现IComparer ,并将该比较传递给SortedSet<>的构造函数,以指示您希望玩家进入的顺序。例如,您可以:

 public class PlayerNameComparer : IComparer { public int Compare(Player x, Player y) { // TODO: Handle x or y being null, or them not having names return x.Name.CompareTo(y.Name); } } 

然后:

 // Note name change to follow conventions, and also to remove the // implication that it's a list when it's actually a set... SortedSet players = new SortedSet(new PlayerNameComparer()); 

您的Player类需要实现IComparable接口..

http://msdn.microsoft.com/en-gb/library/system.icomparable.aspx

使您的Player类实现IComparable

您的Player类必须实现IComparable接口。 SortedSet按排序顺序保存项目,但如果您没有告诉它如何对它们进行排序(使用IComparable),它将如何知道排序顺序是什么?