如何比较两个对象是否为同一对象
如何比较两个实例是否为同一实例?如student1和student2两个对象如何确定他们是否是代表同一实例对象?首先如果两个对象都是对同一类的实例化对象的引用,那么这两个对象必然是同一对象的实例。如果比较的对象分别为两个实例化对象,判断这两个实例相等的要求是两个实例对象的属性对应相等。
对象引用
所谓对象引用是说对象没有进过实例化跟初始化而是直接引用另一个实例化并初始化的对象。如
[vb]
Public Class Student
Private _age As Long
Private _name As String
Private _易做图 As String
Public Sub New()
End Sub
Public Property 易做图
Set(ByVal value)
Me._易做图 = value
End Set
Get
Return Me._易做图
End Get
End Property
Public Property age
Set(ByVal value)
Me._age = value
End Set
Get
Return Me._age
End Get
End Property
Public Property name
Set(ByVal value)
_name = value
End Set
Get
Return _name
End Get
End Property
End Class
[vb]
Module Module1
Sub Main()
Dim student1 As New Student
student1.age = 18
student1.name = "wangming"
student1.易做图 = "男"
Dim student2 As Student
student2 = student1
End Sub
End Module
很明显student1是对Student的实例化,而student2并没有实例化只是对student1的引用所以student1与student2比然相等(student1与student2的姓名、年龄、性别都相同)
两个对象所有属性都相同
如果相比较的两个对象分别来自于类的实例化并经过了初始化,判断他们是否为同一实例就要看他们的属性是否都相同。如:
[vb]
Module Module1
Sub Main()
Dim student1 As New Student
student1.age = 18
student1.name = "wangming"
student1.易做图 = "男"
Dim student2 As New Student
student2.age = 18
student2.name = "wangming"
student2.易做图 = "男"
End Sub
End Module
很明显student1与student2都是对Student的实例化,所以为两个对象。由于student1与student2的姓名、年龄、性别都相同,所以可以判断student1与student2为同一个学生。
判断两个实例是否为同一实例方法的实现
所有的类都继承了一个Equals方法,Equals方法用来与同类对象之间的比较。所以要实现两个对象间的比较就要对该方法进行override(重写)。即要实现两个student间的比较就要在Student类中重写该方法
[vb]
Public Class Student
Private _age As Long
Private _name As String
Private _易做图 As String
Public Sub New()
End Sub
Public Property 易做图
Set(ByVal value)
Me._易做图 = value
End Set
Get
Return Me._易做图
End Get
End Property
Public Property age
Set(ByVal value)
Me._age = value
End Set
Get
Return Me._age
End Get
End Property
Public Property name
Set(ByVal value)
_name = value
End Set
Get
Return _name
End Get
End Property
Public Overrides Function Equals(ByVal obj As Object) As Boolean
Dim stu As Student = obj
Dim flag As Boolean = False
If IsDBNull(stu) Then
flag = False
ElseIf Me Is stu Then ‘判断是否为对象的引用
flag = True
ElseIf Me._易做图 = stu.易做图 And Me._age = stu.age And Me._name = stu.name Then ’判断两个对象的属性是否完全相同
flag = True
Else
flag = False
End If
Return flag
End Function
End Class
[vb]
Module Module1
Sub Main()
'Dim student1 As New Student
'student1.age = 18
'student1.name = "wangming"