[英]C# reference comparison
Does someone know what might go wrong, when you attempt to compare two System.Drawing.Image
entities? 当您尝试比较两个
System.Drawing.Image
实体时,有人知道可能出现的问题吗?
I have some IEnumerable<Image> images
, which is constructed iteratively using Image.FromFile(path)
method. 我有一些
IEnumerable<Image> images
,它是使用Image.FromFile(path)
方法迭代构造的。
But the following code yields the result I can't quite understand: 但是下面的代码产生了我无法理解的结果:
foreach (var image1 in images)
{
foreach (var image2 in images)
{
if (image1 == image2)
{
// (Do something!)
}
}
}
The thing is that the (Do something!)
part never gets called. 事情是
(Do something!)
部分永远不会被调用。
Debugger shows that the image objects have a property called nativeImage
, which, as I assume is a raw memory pointer, because System.Drawing.Image
is implemented using marshalling. 调试器显示图像对象有一个名为
nativeImage
的属性,我假设它是一个原始内存指针,因为System.Drawing.Image
是使用编组实现的。
This memory pointer is changed all the time and I guess some sort of cloning happens here, but I can't understand what should I actually do. 这个内存指针一直在变化,我猜这里发生了某种克隆,但我无法理解我应该做什么。
What am I doing wrong and how can I actually compare System.Drawing.Image
objects taken from one IEnumerable<>
sequence to see if they are the same? 我做错了什么,我怎么能真正比较从一个
IEnumerable<>
序列中获取的System.Drawing.Image
对象,看看它们是否相同?
Thank you. 谢谢。
var paths = new List<String> {"Tests/1_1.jpg", "Tests/1_2.jpg"};
IEnumerable<Image> images = paths.Select(path => Image.FromFile(path)).ToList();
foreach (var image1 in images)
{
foreach (var image2 in images)
{
if (ReferenceEquals(image1, image2))
{
}
}
}
Without the ToList()
, this obviously didn't work, I'm very stupid. 没有
ToList()
,这显然不起作用,我非常愚蠢。
Thanks everyone. 感谢大家。
Remember that each time you call GetEnumerator
you will see new objects returned for each call to MoveNext
. 请记住,每次调用
GetEnumerator
您都会看到每次调用MoveNext
返回的新对象。 What you need to do is force the iteration into a list. 您需要做的是强制迭代到列表中。
var imageList = images.ToList();
By image1 == image2
you're only comparing the references of the image (not image as pixel by pixel). 通过
image1 == image2
您只是比较图像的参考(不是图像逐像素)。
By invoking Image.FromFile(path)
you create new image object every time you call this method (even if the path is the same) so they always have different references. 通过调用
Image.FromFile(path)
,每次调用此方法时都会创建新的图像对象(即使路径相同),因此它们始终具有不同的引用。
I don't know if there is a method to compare images pixel by pixel, but of course you can implement your own mechanism for it (it doesn't look difficult). 我不知道是否有一种方法可以逐像素地比较图像,但当然你可以为它实现自己的机制(看起来并不困难)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.