Array UserControl, ogni controllo ha un metodo per impostare il testo di un'etichetta lì, ma ottenendo una NullReferenceException. Aiuto!

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

Domanda

Quindi, creo un array:

TorrentItem[] torrents = new TorrentItem[10];

Il controllo TorrentItem ha un metodo chiamato SetTorrentName (nome stringa) :

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

Sto usando un ciclo for per popolare 10 TorrentItem in questo modo:

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?
    }  
È stato utile?

Soluzione

Si crea una matrice di riferimenti a 10 oggetti, ma non si creano i 10 oggetti nella matrice. Tutti gli elementi dell'array sono null fino a quando non vengono inizializzati altrimenti.

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

Tuttavia, l'inizializzazione del nome potrebbe probabilmente essere messa nel costruttore.

Altri suggerimenti

Devi inizializzare ogni singolo 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?
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top