c# - Declaring an Array from a Class in C#
问题描述
I want to create an Array of "Highscore" objects that I defined with a class.
I'm always getting a NullReferenceException when I try to set or read the Value of a specific Array content.
It does work when I use a single Highscore object instead of an Array.
It also does work when I use an integer array instead of an Highscore Array.
Code
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[] was null.
解决方案
in this code:
Highscore[] highscoresArray = new Highscore[10];
you instantiate an array of Highscore objects but you do not instantiate each object in the array.
you need to then do
for(int i = 0; i < highscoresArray.Length; i++)
highscoresArray[i] = new Highscore();
推荐阅读
- ansible - 是否可以将 with_dict 与 with_items 结合使用?
- spring - 配置 Spring Security 5 Oauth 2 以使用 access_token uri 参数
- mysql - 将 sql 文件返回到 mysql 数据库时抑制警告
- php - 输入文件的表单编辑
- visual-studio - 创建或打开解决方案时出现 Visual Studio 2017 错误
- r - R正则表达式替换可变数量的周期之后的所有周期,前面有空格/行首
- outlook - 如何使用具有正确序列号的 ICS 更新 Outlook AppointmentItem?即如何确定序号?
- powerbi - 我们如何在 Switch 和 Format 函数中分配前缀字符
- android - 更新到 Android Studio 3.2 后构建失败
- visual-studio-code - 从没有 Gnome/KDE 的无头 linux 服务器运行 VS-Code / X11