1

このコードを実行しようとすると NullReferenceException was unhandled エラーが発生し続け、その理由がわかりません。私は約4か月間c#でしか作業していない人の名前で並べ替えようとしています。

    public static student[] players = new student[30];
    public struct student
    {
        public string lastname;
        public string firstname;
        public string likes;
    }

    public static void read()
    {
        StreamReader sr = new StreamReader(@"names.txt");
        int i = 0;
        while (!sr.EndOfStream)
        {
            players[i].lastname = sr.ReadLine();
            players[i].firstname = sr.ReadLine();
            players[i].likes = sr.ReadLine();
            i++;
        }
        sr.Close();
    }

        public static void sort()
        {
            //alphabetically lists players
            student temp;

            for (int i = 0; i < players.Length - 1; i++)
            {
                for (int pos = 0; pos < players.Length - 1; pos++)
                {

                    if (players[pos + 1].lastname.CompareTo(players[pos].lastname) < +0)
                    {
                        temp = players[pos + 1];
                        players[pos + 1] = players[pos];
                        players[pos] = temp;
                    }
                }
            }

        }
4

3 に答える 3

1

NullReference をキャッチした可能性があります

while (!sr.EndOfStream)
{
    player[i] = new student();
    players[i].lastname = sr.ReadLine();
    players[i].firstname = sr.ReadLine();
    players[i].likes = sr.ReadLine();
    i++;
}
于 2013-11-13T02:05:13.660 に答える