与Properties.Resources.image的图像比较 [英] Image comparison to Properties.Resources.image

查看:66
本文介绍了与Properties.Resources.image的图像比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能告诉我以下条件为何为假吗?

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
{
    ...
}

即使我写:

SelectedImages[0] = Properties.Resources.my_image;
if (SelectedImages[0] == Properties.Resources.my_image)     // false
{
    ...
}

如何进行比较?

推荐答案

它们不相等,因为Properties.Resources会制作图像的副本,并将该副本返回给您的代码。每次获得该图像时,您实际上就是在创建一个全新的Image对象。之所以进行复制,是因为资源通常应像常量一样工作。如果您(例如)以某种方式修改了图片,您就不想让代码更改图片。

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.

那么代码中会发生什么呢?最后,您比较了两个恰好包含相同数据的不同图像对象。 .NET看到您有两个 different 对象,并返回false。它不会进行深度比较,以查看对象是否具有相同的数据/状态。

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.

这里是指向文章的链接,该文章解释了发生的情况较高级别: https: //navaneethkn.wordpress.com/2009/10/15/understanding-equality-and-object-comparison-in-net-framework/

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解决问题的快速方法是逐个像素比较资源图像和SelectedImage图像,以查看它们是否相等。这显然会表现不佳。另一种更有效的方法可能是建立字典并使用键来跟踪图像的原始来源。

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.

这篇关于与Properties.Resources.image的图像比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆