问题
Could you tell me why is the following condition false?
List<Image> SelectedImages = new List<Image>();
SelectedImages.Add(Properties.Resources.my_image);
if (SelectedImages[0] == Properties.Resources.my_image) // false
{
...
}
Even if I write:
SelectedImages[0] = Properties.Resources.my_image;
if (SelectedImages[0] == Properties.Resources.my_image) // false
{
...
}
How can I make this comparison work?
回答1:
They're not equal because Properties.Resources makes a copy of the image and returns that copy back to your code. Everytime you get that image, you're effectively creating an entirely new Image object. It makes a copy because resources should ordinarily behave like constants. You wouldn't want your code to change the picture if you (for example) modified the picture in some way.
So what happens in your code? You end up comparing two different image objects that happen to contain the same data. .NET sees that you have two different objects and returns false. It doesn't do a "deep" comparision to see if the objects have the same data/state.
Here's a link to an article that explains what is going on at a high level: https://navaneethkn.wordpress.com/2009/10/15/understanding-equality-and-object-comparison-in-net-framework/
A quick way to workaround your problem would be to compare the Resource image and your SelectedImage Image pixel by pixel to see if they are "equal". This would obviously perform poorly. Another, more efficient way might be to build a dictionary and use a key to track where the image originally came from.
回答2:
Just use the Tag
property in the Image object. You can store anything you want in there. Just set up your image like this...
Image img_dbActive = MyApp.Properties.Resources.tray_icon_database_active;
img_dbActive.Tag = "tray_icon_database_active";
Image img_dbIdle = MyApp.Properties.Resources.tray_icon_database_idle;
img_dbIdle.Tag = "tray_icon_database_idle";
ToolStripStatusLabel lbl = new ToolStripStatusLabel("Database is doing something...", img_dbActive);
lbl.Image.Tag = "tray_icon_database_active";
if (lbl.Image.Tag == img_dbActive.Tag)
{
//Images match
}
来源:https://stackoverflow.com/questions/17200837/image-comparison-to-properties-resources-image