空指针错误 C#

本文关键字:错误 空指针 | 更新日期: 2023-09-27 18:31:20

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TacticalCheeseRacer
{
    class Program
    {
        static int playerNum;
        static int totalPlayers;
        static Player[] players = new Player[4];
        struct Player
        {
            public string Name;
            public int Pos;
        }
        private static void PlayerTurn(int playerNo, int distance)
        {
            // TODO: Makes a move for the given player
        }
        static void ResetGame()
        {
            // TODO: get the number of players and set their positions at 0
        }
        static void GameTurn()
        {
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Enter total number of players for game:");
            totalPlayers = int.Parse(Console.ReadLine());
            for (int i = 0; i < totalPlayers; i++)
            {
                Player p;
                Console.WriteLine("Enter player's details:");
                Console.WriteLine("Name:");
                p.Name = Console.ReadLine();
                Console.WriteLine("Position:");
                p.Pos = int.Parse(Console.ReadLine());
                players[i] = p;
                playerNum++;
            } //while (playerNum < totalPlayers);
            for (int i = 0; i < totalPlayers; i++)
            {
                Console.WriteLine(players[i]); // test to see if it works
            }
        }
    }
    // store player positions in arrays
}

Unhandled Exception: System.ArgumentNullException: Argument cannot be null.
Parameter name: s
  at System.Int32.Parse (System.String s) [0x00000] in <filename unknown>:0 
  at TacticalCheeseRacer.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0

似乎找不到错误 any1 有什么想法吗?

空指针错误 C#

所以你的问题在行:

totalPlayers = int.Parse(Console.ReadLine());

正如你的错误所见。解决此问题的最简单方法如下:

if(int.TryParse(Console.ReadLine(), out totalPlayers)) {
   // continue your normal logic here
} else {
   // uh oh, couldn't parse the number show a message to the user and exit gracefully
}

使用int.TryParse您尝试解析,如果成功,您可以继续正确设置totalPlayers。如果不成功,则可以正常退出,而不是引发异常。

底线,如果你从用户那里得到输入,你不能信任它,所以你应该使用TryParse这样他们就不会造成不良数据的问题。