c# PictureBox 总是抛出 NullReferenceException

c# PictureBox always throws NullReferenceException

我有一个方法可以从数组中删除所有旧图片并添加新图片,但它会在最后一行抛出 System.NullReferenceException。

PictureBox[] selectedCards = new PictureBox[0];
byte selectedCardsCount = 0;
int selectedCardsIndex = 0;

private void AddSelectedCard(int index, PictureBox newCard)
        {
            if (selectedCards.Length != 0)
            {
                foreach (PictureBox card in selectedCards)
                {
                    this.Controls.Remove(card);
                }
            }

            selectedCardsCount++;

            selectedCards = new PictureBox[selectedCardsCount];

            selectedCards[selectedCardsIndex].Image = new Bitmap(newCard.Image); //The exception is thrown on this line

            selectedCardsIndex++;
    }

当我调试程序时:

selectedCards[selectedCardsIndex] 为 0(非空)

newCard.Image 是 System.Drawing.Bitmap(也不为空)

你在这一行

创建了一个新的PictureBox数组
selectedCards = new PictureBox[selectedCardsCount];

但这只会创建数组,而不是 PictureBox 本身。所以你需要创建它们:

selectedCards[selectedCardsIndex] = new PictureBox();
this.Controls.Add(selectedCards[selectedCardsIndex]);

selectedCards[selectedCardsIndex].Image = new Bitmap(newCard.Image);