在 C# 中从 Class 声明一个数组

Declaring an Array from a Class in C#

我想创建一个 "Highscore" 对象数组,我用 class.
定义了这些对象 当我尝试设置或读取特定数组内容的值时,我总是收到 NullReferenceException。

当我使用单个 Highscore 对象而不是数组时它确实有效。

当我使用整数数组而不是 Highscore 数组时,它也有效。

代码

class Highscore
{
    public int score;
}
class Program
{
    static void Main()
    {
        Highscore[] highscoresArray = new Highscore[10];
        highscoresArray[0].score = 12;
        Console.WriteLine(highscoresArray[0].score);
        Console.ReadLine();
    }
}

System.NullReferenceException:

highscoresArray[] 为空。

在此代码中:

Highscore[] highscoresArray = new Highscore[10];

您实例化了一个 Highscore 对象数组,但没有实例化数组中的每个对象。

然后你需要做

for(int i = 0; i < highscoresArray.Length; i++)
    highscoresArray[i]  = new Highscore();

也许您需要初始化数组的每一项:

 for (int i = 0; i < highscoresArray.length; i++)
 {
      highscoresArray[i] = new Highscore();
 }

你必须先在数组中添加一个高分,例如:

highscoresArray[0] = new Highscore();

那是因为您创建了一个数组,设置了它的长度,但实际上从未实例化它的任何元素。一种方法是:

Highscore[] highscoresArray = new Highscore[10];
highscoresArray[0] = new Highscore();

.. 或者使用结构

struct Highscore
{
    public int score;
}