UserControl数组,每个控件都有一个方法来设置标签的文本,但是得到一个NullReferenceException。救命!

StackOverflow https://stackoverflow.com/questions/1613350

所以,我创建了一个数组:

TorrentItem[] torrents = new TorrentItem[10];

TorrentItem 控件有一个名为 SetTorrentName(字符串名称)的方法

private void SetTorrentName(string Name)
{
    label1.Text = Name;
}

我正在使用for循环来填充10个TorrentItems,如下所示:

private TorrentItem[] GetTorrents()
{
    TorrentItem[] torrents = new TorrentItem[10];
    string test = "";

    for (int i = 0; i < 10; i++)
    {
          test = i.ToString();
          TorrentItem[i].SetTorrentName(test); //I get a null reference error here. 
          //What am I doing wrong?
    }  
有帮助吗?

解决方案

您可以创建对10个对象的引用数组,但不要在数组中创建10个对象。所有数组元素都是 null ,直到初始化为止。

for( int i = 0; i < 10; ++i )
{
    torrents[i] = new TorrentItem();
    /* do something with torrents[i] */
}

但是,名称初始化可能会被放入构造函数中。

其他提示

您需要初始化每个TorrentItem:

for (int i = 0; i < 10; i++)
{
      TorrentItem[i] = new TorrentItem(); //Initialize each element of the array
      test = i.ToString();
      TorrentItem[i].SetTorrentName(test); //I get a null reference error here. 
      //What am I doing wrong?
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top