Winforms 类型为';的未处理异常;System.NullReferenceException';发生在System.Windows.Forms.dll中
好吧,我正在编写一个Yachzee游戏,但它的效果并不好 当我点击“滚动”按钮时,这个代码就开始了Winforms 类型为';的未处理异常;System.NullReferenceException';发生在System.Windows.Forms.dll中,winforms,visual-studio-2012,c++-cli,Winforms,Visual Studio 2012,C++ Cli,好吧,我正在编写一个Yachzee游戏,但它的效果并不好 当我点击“滚动”按钮时,这个代码就开始了 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 (ra
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);
如果我移动表示
p->ImageLocation = "..\\Bilder\\dice_face_1.png";
p->Size = System::Drawing::Size(91, 85);
在else下,更改SizeMode的行所在的位置将断开,箭头指向if、else if或else,其数字对应于rand的值。如果我看下面,它似乎显示了变量的所有不同值,它会显示这一点
Name | Value | Type
_________________________________________________________________
this | 0x02b6e9a4 { rand=1 p=<undefined value> } | Dice^
Name | Value |类型
_________________________________________________________________
这个| 0x02b6e9a4{rand=1p=}|骰子^
最后要补充的是,它在“中断”弹出窗口中显示以下内容
其他信息:对象引用未设置为对象的实例。您需要创建PictureBox控件的实例,并将其作为子控件添加到窗体或容器控件。运行程序时,异常设置窗格将显示在vs的底部。打开它,然后在搜索框中键入NullReferenceException并选中System.NullReferenceException框 您不分配
图片盒
。它只是一个null
变量。您不能在null
上设置Size
,它就是不起作用。您需要首先创建PictureBox
的实例<代码>PictureBox ^p=新PictureBox()代码>或类似。(我不记得确切的语法)可能的副本我看不到C代码和C++代码,只有C++ + CLI和Windows窗体。我已经更新了标签来替换这个。另外,如果您打算使用C++/CLI,我建议您使用而不是C库rand()
@EBrown-这是我注释掉的那一行中所做的吗?(createPictureBox函数中的第一个函数)如果没有,那么是如何完成的?@Trisstar是。这就是应该做的事情。这是在我评论的那条线上做的事情吗?(createPictureBox函数中的第一个)如果没有,如何完成?部分是。。。不要忘记将控件添加到表单层次结构。另一种解决方案是重用表单上已有的图片框控件。固定数量的骰子对于重用现有控件可能更有意义。