List.Contains返回false,即使看起来应该返回true [英] List.Contains returns false, even though it seems it should return true
问题描述
Sub pageload() Handles Me.Load
Dim bom As New List(Of Car)
Dim car1 As New Car With {.Name = "Pea", .Year = 2}
Dim car2 As New Car With {.Name = "Pea", .Year = 2}
bom.Add(car1)
MsgBox(bom.Contains(car2))
End Sub
为什么?我的意思是该对象具有完全相同的数据,那么为什么说它不包含?
WHY??? I mean the object has the exactly same data, so why does it say it is not contained?
推荐答案
Contains
方法通过在对象上调用Equals
方法来测试相等性.除非您重写Car
类中的Equals
方法并实现自己的比较方式,否则Car
的实例将通过引用标识(完全相同的对象)视为相等.不是基于它们的内容相等.
The Contains
method tests equality by calling the Equals
method on objects. Unless you override the Equals
method in the Car
class and implement your own means of comparison, instances of Car
will be considered equal by means of referential identity (being the exact same object) not based on their contents being equal.
您创建的那些对象绝对不是同一对象.证明:改变一个不会改变另一个.
Those objects you created are definitely not the same object. Proof: changing one will not change the other.
这篇关于List.Contains返回false,即使看起来应该返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!