类型' System.NullReferenceException'的未处理异常发生在System.Windows.Forms.dll中

时间:2015-05-18 18:02:45

标签: winforms visual-studio-2012 c++-cli

好的,我正在编写一个Yachzee游戏,好吧,它不能很好地工作。

当我点击按钮" Roll"此代码已启动。

         int rand1 = rand()%6+1;
         int rand2 = rand()%6+1;
         int rand3 = rand()%6+1;
         int rand4 = rand()%6+1;
         int rand5 = rand()%6+1;

         Dice^ t1 = gcnew Dice (rand1);
         Dice^ t2 = gcnew Dice (rand2);
         Dice^ t3 = gcnew Dice (rand3);
         Dice^ t4 = gcnew Dice (rand4);
         Dice^ t5 = gcnew Dice (rand5);

它会创建五个单独的随机数,并将它们作为五个单独的对象发送到我的Dice.h。

这是Dice.h中的代码

using namespace System::Windows::Forms;

ref class Dice {

public:
    Dice (int rand)
    {
        this->rand = rand;
        createPictureBox();
    }

private:
    int rand;
    PictureBox^ p;

public:
void createPictureBox()
{
        //PictureBox^ p = gcnew PictureBox();

        p->Size = System::Drawing::Size(91, 85);
        if ( rand == 1 )
            p->ImageLocation = "..\\Bilder\\dice_face_1.png";
        else if ( rand == 2 )
            p->ImageLocation = "..\\Bilder\\dice_face_2.png";
        else if ( rand == 3 )
            p->ImageLocation = "..\\Bilder\\dice_face_3.png";
        else if ( rand == 4 )
            p->ImageLocation = "..\\Bilder\\dice_face_4.png";
        else if ( rand == 5 )
            p->ImageLocation = "..\\Bilder\\dice_face_5.png";
        else
            p->ImageLocation = "..\\Bilder\\dice_face_6.png";
        p->SizeMode = PictureBoxSizeMode::StretchImage;
}

public:
PictureBox^ getPictureBox()
{
    return p;
}

int getRand()
{
    return rand;
}

};

就像现在一样,程序中断了一个指向

行的箭头
p->ImageLocation = "..\\Bilder\\dice_face_1.png";

如果我移动说

的行
p->Size = System::Drawing::Size(91, 85);

在else下,其中更改SizeMode的行将会断开,箭头指向if,否则if或者其他数字对应于rand的值。如果我看下面似乎显示变量的所有不同值,它将显示此

Name    |   Value                                       |   Type
_________________________________________________________________

this    |   0x02b6e9a4 { rand=1 p=<undefined value> }   |   Dice^

要添加的最后一件事是它会在中断时弹出

附加信息:未将对象引用设置为对象的实例。

2 个答案:

答案 0 :(得分:0)

您需要创建PictureBox控件的实例,并将其作为子项添加到窗体或容器控件。

答案 1 :(得分:0)

在运行程序时,将在“打开它”的底部显示“异常设置”窗格,然后在搜索框中键入NullReferenceException并检查System.NullReferenceException框。

相关问题