不断获取“未设置为对象实例的对象引用”.复制字符串时
本文关键字:对象引用 复制 字符串 实例 对象 获取 设置 | 更新日期: 2023-09-27 17:49:32
int PlayerAmount = 10;
int CurrentPlayer = 0;
Player[] player = new Player[PlayerAmount];
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")
{
if (CurrentPlayer >= PlayerAmount)
{
Console.WriteLine();
Console.WriteLine("MAX AMOUNT OF PLAYERS HAS BEEN REACHED!");
Console.WriteLine();
}
else
{
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();
//=========================================
//THIS IS WHERE THE ERROR OCCURS===========
//=========================================
player[CurrentPlayer].Name = PlayerName;
Console.WriteLine("Player '"" + player[CurrentPlayer].Name + "'" with the score of '"" + player[CurrentPlayer].Score + "'" has been created successfully!" );
Console.WriteLine();
}
}
else if (Input == "2")
{
Console.WriteLine("Displaying the highscores");
}
else if (Input == "3")
{
Console.WriteLine("Writing to XML file");
}
else
{
Console.WriteLine("INVALID INPUT");
}
}
我已经尝试过使用字符串复制,但这只是给了我同样的错误,我已经在代码中指出了问题,但如果你看不见它的播放器名称被复制的地方:"播放器[CurrentPlayer]。Name = PlayerName;"
Thanks in advance
不初始化Player
数组的每个成员。后做:
Player[] player = new Player[PlayerAmount];
你可能也想这样做:
for (int i = 0; i < PlayerAmount; i++)
{
Player[i] = new Player();
}
因为事先,数组只包含一堆null
引用
看起来像:
player[CurrentPlayer].Name
是null。确保在currentPlayer
索引处的播放器对象不为空。
初始化数组时,所有对象默认为null(非原语)。因此,您必须实例化数组中的每个索引中的每个播放器。
这一行:
Player[] player = new Player[PlayerAmount];
只分配一个大小为playerAmount
的数组(在您的示例中为10);
你需要这个来初始化它们:
for(int i =0; i < player.length;i++)
{
player[i] = new Player();
}
你也可以创建像
这样的"lazy-like"player[CurrentPlayer] = new Player();
player[CurrentPlayer].Name = PlayerName;