所以我试图创建一个简单的程序,只需在单击图片框中更改图片即可。我目前只使用两张图片,所以我的图片框单击事件函数的代码
看起来像这样:
private void pictureBox1_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == Labirint.Properties.Resources.first)
pictureBox1.Image = Labirint.Properties.Resources.reitmi;
else if (pictureBox1.Image == Labirint.Properties.Resources.reitmi)
pictureBox1.Image = Labirint.Properties.Resources.first;
}
由于某种原因, if 语句不起作用并且图片没有改变。
我应该怎么办?
注意:原始代码包含第二个错误if
撤销第一个 if 条件的效果would使用建议的修复程序西拉尔的回答 https://stackoverflow.com/a/27749566/477420,但添加else
没有解决问题 - 单步执行代码else
仍然显示任何图像都没有匹配项。
if (pictureBox1.Image == Labirint.Properties.Resources.first)
pictureBox1.Image = Labirint.Properties.Resources.reitmi;
if (pictureBox1.Image == Labirint.Properties.Resources.reitmi) // was missing else
pictureBox1.Image = Labirint.Properties.Resources.first;
if (pictureBox1.Image == Labirint.Properties.Resources.first)
这里有一个陷阱,没有足够的 .NET 程序员意识到。负责一个lot运行内存占用过多的程序。使用 Labirint.Properties.Resources.xxxx 属性创建一个newimage 对象,它永远不会匹配任何其他图像。您只需使用该属性一次,将图像存储在类的字段中。大致:
private Image first;
private Image reitmi;
public Form1() {
InitializeComponent();
first = Labirint.Properties.Resources.first;
reitmi = Labirint.Properties.Resources.reitmi;
pictureBox1.Image = first;
}
现在您可以比较它们:
private void pictureBox1_Click(object sender, EventArgs e) {
if (pictureBox1.Image == first) pictureBox1.Image = reitmi;
else pictureBox1.Image = first;
}
并避免内存膨胀:
private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
first.Dispose();
reitmi.Dispose();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)