C#中的indexoutofrangeexception

use*_*553 1 c#

任何人都可以帮我解决问题吗?

struct Player
{
    public string Name;
    public int X;
    public int Y;
}
static Player[] players = new Player[amountofPlayers];

static void ResetGame() {
    Console.WriteLine("Welcome to the game!");
    Console.Write("How many player will be taking part today: ");
    string playerNo = Console.ReadLine();
    amountofPlayers = int.Parse(playerNo);
    if (amountofPlayers <= 4)
    {
        for (int i = 0; i < amountofPlayers; i = i + 1)
        {
            int displayNumber = i + 1;
            Console.Write("Please enter the name of player " + displayNumber + ": ");
            players[i].Name = Console.ReadLine(); //error is here
        }
    }
    else
    {
        Console.WriteLine("Please enter a number of players less than 4!");
    }
}

static int amountofPlayers;
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

这一行:

static Player[] players = new Player[amountofPlayers];
Run Code Online (Sandbox Code Playgroud)

amountOfPlayers在根据用户输入分配值之前执行.因此amountOfPlayers它的默认值为0,并且您正在创建一个包含0个元素的数组.

我建议你只声明变量:

 static Player[] players;
Run Code Online (Sandbox Code Playgroud)

然后在你的方法中创建amountOfPlayers一个局部变量,ResetGame在你询问有多少玩家之后初始化数组:

static void ResetGame() {
    Console.WriteLine("Welcome to the game!");
    Console.Write("How many player will be taking part today: ");
    string playerNo = Console.ReadLine();
    int amountofPlayers = int.Parse(playerNo);
    players = new Player[amountOfPlayers];
    ...
}
Run Code Online (Sandbox Code Playgroud)

建议创建Player一个类而不是结构,保持字段私有,并使用属性.