因此,我正在尝试创建一个简单的程序,该程序仅在单击图片框时更改图片。我现在只使用两张图片,所以我的图片框点击事件函数代码 看起来像这样:
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 条件的效果将与 Cyral's answer 建议的修复一起工作,但添加 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 程序员意识到这一点。负责大量内存占用过大的程序。很多。使用 Labirint.Properties.Resources.xxxx 属性创建一个新图像对象,它永远不会匹配任何其他图像。您只需使用该属性一次,将图像存储在您类(class)的一个字段中。大致:
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();
}
关于c# - 如何检查图像对象是否与资源中的对象相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27749541/