[英]Why can't my C# code find out when two objects are identical?
This is a method for recursively searching through a binary tree that is filled with objects of the various child classes of the class Photo. 这是一种用于递归搜索二叉树的方法,该二叉树充满了Photo类的各个子类的对象。
public void SearchForIdentical(Photo searched)
{
SearchForIdentical(ref root, searched);
}
void SearchForIdentical(ref TreeNode current, Photo searched)
{
try
{
if(current != null)
{
if(current.content.Equals(searched))
{
throw new PhotoAlreadyExistsException(searched);
}
SearchForIdentical(ref current.left, searched);
SearchForIdentical(ref current.right, searched);
}
}
catch (PhotoAlreadyExistsException e)
{
Console.WriteLine("This photo already exists! Try a new one!");
}
}
A 'photo' is defined by the value of its various arguments and properties (the child classes don't necessarily all have the same kind of arguments and properties). “照片”由其各种参数和属性的值定义(子类不一定都具有相同类型的参数和属性)。 If the user types in a new photo, that is fully identical in all its arguments and properties with an existing one, this method should notice it, and throw an exception.
如果用户键入一张新照片,其所有参数和属性都与现有照片完全相同,则此方法应予以注意,并引发异常。
The problem is, it never happens. 问题是,它永远不会发生。 When I debugged it, it seemed the program never assigns true to the premise
current.content.Equals(searched)
, even when the two object is exactly identical. 当我调试它时,即使两个对象完全相同,该程序似乎也从未将true赋给前提
current.content.Equals(searched)
。
What could be the problem? 可能是什么问题呢?
If you never override the Equals()
method in the Photo
class to do the comparisons of the properties you've described, your code will be doing an object reference equality comparison. 如果您从不重写
Photo
类中的Equals()
方法来对您描述的属性进行比较,则您的代码将进行对象引用相等性比较。
This would explain why when the properties are identical, the Equals()
method returns false
. 这可以解释为什么当属性相同时,
Equals()
方法返回false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.