【问题标题】:Declaring an Array from a Class in C#在 C# 中从类中声明一个数组
【发布时间】:2020-03-02 20:25:42
【问题描述】:

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

当我使用单个 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[] 为空。

【问题讨论】:

标签: c# arrays class declare


【解决方案1】:

在这段代码中:

Highscore[] highscoresArray = new Highscore[10];

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

你需要这样做

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

【讨论】:

    【解决方案2】:

    你要先给数组加一个高分,例如:

    highscoresArray[0] = new Highscore();
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          【解决方案5】:

          .. 或者使用结构体

          struct Highscore
          {
              public int score;
          }
          

          【讨论】:

          • 结构的缺点/优点是什么?
          • @JoshuaDrake 特别是在这种情况下 - 不需要初始化。
          • 评论来自审核队列,我们​​希望答案包括原因,而不仅仅是代码。
          猜你喜欢
          • 2020-02-15
          • 2016-12-09
          • 1970-01-01
          • 1970-01-01
          • 2010-10-30
          • 2011-02-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多