صفيف 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 كائنات، لكن لا تقم بإنشاء الكائنات العشرة في الصفيف.جميع عناصر المصفوفة موجودة 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