少なくとも1つのオブジェクトはIComparableを実装する必要があります質問する

少なくとも1つのオブジェクトは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<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");
                }
            }
        }
    }
}

だから私は「

少なくとも 1 つのオブジェクトが IComparable を実装する必要があります。

「2 番目のプレーヤーを追加しようとすると、最初のプレーヤーは機能しますが、2 番目のプレーヤーは機能しません。SortedSetこれは作業の要件であり、学校の課題であるため、使用する必要があります。」

ベストアンサー1

...を使用しようとしている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());

おすすめ記事