Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

c# - How to check if image object is the same as one from resource?

So I'm trying to create a simple program that just change the picture in a picture box when it's clicked. I'm using just two pictures at the moment so my code for the picture box click event function looks like that:

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;
    }

For some reason the if statement it's not working and the picture don't change. What should I do?


Note: original code contained bug with second if undoing effect of first if condition would work with fix suggested by Cyral's answer, but adding else did not fix the issue - stepping through the code with else still shows no matches for either image.

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; 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
     if (pictureBox1.Image == Labirint.Properties.Resources.first)

There's a trap here that not enough .NET programmers are aware of. Responsible for a lot of programs that run with bloated memory footprints. Using the Labirint.Properties.Resources.xxxx property creates a new image object, it will never match any other image. You need to use the property only once, store the images in a field of your class. Roughly:

    private Image first;
    private Image reitmi;

    public Form1() {
        InitializeComponent();
        first = Labirint.Properties.Resources.first;
        reitmi = Labirint.Properties.Resources.reitmi;
        pictureBox1.Image = first;
    }

And now you can compare them:

    private void pictureBox1_Click(object sender, EventArgs e) {
        if (pictureBox1.Image == first) pictureBox1.Image = reitmi;
        else pictureBox1.Image = first;
    }

And to avoid the memory bloat:

    private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
       first.Dispose();
       reitmi.Dispose();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...