【问题标题】:ListBoxItem is null (NullReferenceException) even though it is initializedListBoxItem 为 null (NullReferenceException),即使它已初始化
【发布时间】: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 中开发了相同的应用程序,但代码几乎相同,而且它没有初始化问题。

关于为什么会发生这种情况的任何想法?

【问题讨论】:

    标签: c# .net-core uwp


    【解决方案1】:

    new ListBoxItem[512] 只初始化一个空数组。在此之后,您需要创建一个 ListBoxItem 类型的对象并将其添加到您想要的数组单元之一。

    试试这个

    ListBoxItem[] item = new ListBoxItem[512]; //array initialization
    for (int i = 0; i <= 511; i++)
    {
    ListBoxItem itm = new ListBoxItem();  //object initialization
    itm.Content = "Preset " + (i + 1) + ":" + presets[i];
    item[i]=itm;
    }
    

    【讨论】:

    • 它完美无缺。谢谢!你能解释一下为什么我需要初始化第二个 ListboxItem 吗?
    • 不客气。我在回答中添加了一些解释。
    • 我现在明白了。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 2021-02-21
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    相关资源
    最近更新 更多