【发布时间】:2021-06-01 01:33:48
【问题描述】:
我正在用 c# 编写一个程序,其中有一个类的对象数组。我在类中有一个构造函数,它应该给附加的字符串一个“”值,以确保它们是空的,这样信息就可以轻松传递。然后我创建了这样的数组:
参与者[8][8] 网格 = 新参与者[8][];
但是我被抛出一个 NullReferenceExcetption 错误。这是我的代码供您参考。
using System;
namespace TreasurehuntCsharp
{
class square
{
public string strX = "";
public int y = 0;
public int x = 0;
}
class participants
{
public string name = "";
public string contact = "";
public participants()
{
name = "";
contact = "";
}
}
class Program
{
//Method for user to choose a square
static void Input(square Coord)
{
//Variables
bool correct = false;
//Inputs
Console.WriteLine("Please enter the coordinates of the square you would like to select: \r\n");
do
{
//X coordinate
Console.WriteLine("X: ");
Coord.strX = Console.ReadLine().ToLower();
//Convert letter to array coordinate
switch (Coord.strX)
{
case "a":
Coord.x = 0;
correct = true;
break;
case "b":
Coord.x = 1;
correct = true;
break;
case "c":
Coord.x = 2;
correct = true;
break;
case "d":
Coord.x = 3;
correct = true;
break;
case "e":
Coord.x = 4;
correct = true;
break;
case "f":
Coord.x = 5;
correct = true;
break;
case "g":
Coord.x = 6;
correct = true;
break;
case "h":
Coord.x = 7;
correct = true;
break;
default:
Console.WriteLine("Please enter a letter from A to H");
correct = false;
break;
}
} while (correct != true);
correct = false;
do
{
//Y coordinate
Console.WriteLine("Y: ");
Coord.y = Convert.ToInt32(Console.ReadLine());
if (Coord.y >= 1 && Coord.y <= 7)
{
correct = true;
}
else
{
Console.WriteLine("Please input an integer value from 1 to 7.");
correct = false;
}
} while (correct != true);
}
static void ParticipantDetails(participants User)
{
Console.WriteLine("Please input your name and Contact number: ");
//User name input
Console.WriteLine("Name: ");
User.name = Console.ReadLine();
//User contact number input
Console.WriteLine("Number: ");
User.contact = Console.ReadLine();
}
static void Main(string[] args)
{
//Objects
square Coord = new square();
participants User = new participants();
//Initialise 2D array
participants[][] grid = new participants[8][];
//Variables
bool correct = false;
do
{
//Methods
Input(Coord);
ParticipantDetails(User);
//Input data to array
if (grid[Coord.x][Coord.y].name == "" && grid[Coord.x][Coord.y].contact == "")
{
grid[Coord.x][Coord.y].name = User.name;
grid[Coord.x][Coord.y].contact = User.contact;
Console.WriteLine(grid[Coord.x][Coord.y]);
correct = true;
}
else
{
Console.WriteLine("That square is already filled. Please try again.");
correct = false;
}
} while (correct == false);
}
}
【问题讨论】:
-
哪一行抛出异常?你能把所有无关紧要的代码都去掉,然后创建一个minimal reproducible example吗?
-
participants[][]这称为锯齿状数组(数组的数组)。您只初始化数组数组,而不是其中的数组,因此它们将为空。participants也是一个类,所以它的默认值也将是null,所以你还需要在其中初始化每个participant(或者根据需要更改逻辑来执行此操作)
标签: c# arrays .net oop nullreferenceexception