【发布时间】:2021-11-18 10:46:28
【问题描述】:
我正在开发一个 UWP 应用程序,我需要在其中将文件的一些内容显示为 ListBox 中的条目,如下所示:
我设法读取了文件并使用了我想要的部分,但我偶然发现了一个对我来说没有意义的错误。
应用程序会为我正在使用的 ListBoxItem 数组引发 NullReferenceException,即使我在 for 循环之前已对其进行了初始化。
这是我编写的部分代码:
ListBoxItem[] item = new ListBoxItem[512]; //object initialization
for (int i = 0; i <= 511; i++)
{
item[i].Content = "Preset " + (i + 1) + ":" + presets[i];
//presets[] is an array I'm using to store the file contents before "merging" them to the item[] array
}
listBox1.Items.Clear();
listBox1.Items.Add(item); //after clearing the ListBox, display the contents of new file
我确实使用断点检查了该部分,并且似乎 item[] 数组为空,即使我已经对其进行了初始化。我还阅读了其他帖子(例如this one),这些帖子大多是被遗忘的初始化。但是,NullReferenceException 上的 this answer 的一部分表明该数组已分配但从未真正初始化。
我很茫然,因为前段时间我确实在 WinForms 中开发了相同的应用程序,但代码几乎相同,而且它没有初始化问题。
关于为什么会发生这种情况的任何想法?
【问题讨论】: