【发布时间】:2021-05-07 01:35:22
【问题描述】:
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<Player> PlayerList = new SortedSet<Player>();
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,因为这是工作的要求,是学校的工作。
【问题讨论】:
-
错误告诉你你需要知道什么——你
Player类必须实现IComparable接口 -
这种错误不应该存在,我们有一个很好的类型安全语言是有原因的,
SortedSet<T>应该真的有一个约束T : IComparable<T> -
使用
ThenBy()而不是实现IComparable<>或IComparer<>。 -
SortedSet
应该确实有一个 T 约束:IComparable - 不,因为那样你就不能在一组对象上使用外部比较器没有自己的。 -
使用 ThenBy() 而不是实现 IComparable 或 IComparer -- 首先,您的意思是
OrderBy。其次,这无济于事......您仍然需要一个比较器(显然......系统不知道如何在没有被告知的情况下订购 Players)。
标签: c#