gpt4 book ai didi

c# - 至少一个对象必须实现 IComparable

转载 作者:IT王子 更新时间:2023-10-29 04:02:16 24 4
gpt4 key购买 nike

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");
}
}
}
}
}

所以我不断收到“

At least one object must implement IComparable.

"当尝试添加第二个播放器时,第一个播放器有效,但第二个播放器无效。我还必须使用 SortedSet,因为这是工作的要求,这是学校作业。

最佳答案

那么,您正在尝试使用 SortedSet<> ...这意味着您关心订购。但听上去你的Player类型未实现 IComparable<Player> .那么您希望看到什么样的排序顺序?

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

public class PlayerNameComparer : IComparer<Player>
{
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<Player> players = new SortedSet<Player>(new PlayerNameComparer());

关于c# - 至少一个对象必须实现 IComparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14141891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com