variedade UserControl, cada controle tem um método para definir o texto de uma etiqueta lá, mas recebendo um NullReferenceException. Socorro!

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

Pergunta

Então, eu criar uma matriz:

TorrentItem[] torrents = new TorrentItem[10];

O TorrentItem controle tem um método chamado SetTorrentName (nome string) :

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

Eu estou usando um loop for para preencher 10 TorrentItems assim:

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?
    }  
Foi útil?

Solução

Você cria um array de referências para 10 objetos, mas você não criar os 10 objetos na matriz. Todos os elementos da matriz são null até inicializado contrário.

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

No entanto, a inicialização nome provavelmente poderia ser colocado no construtor.

Outras dicas

Você precisa inicializar cada TorrentItem individual:

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?
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top