Compare objects in VB.NET

I want to write a function that takes two objects as parameters and compares only the fields contained in the objects. I don’t know what type of objects will be during development, but passed objects will be the classes used in our application.

Is it possible to compare the fields of objects without knowing their types at runtime?

+3
source share
5 answers

Yes, at run time you can find the fields, properties, and methods of objects. You will need to use System.Reflection and find the appropriate fields, make sure the data types are compatible, and then compare the values.

+7
source

To do this, we have all data access classes overriding GetHashCode: for example.

Public Overrides Function GetHashCode() As Integer
    Dim sb As New System.Text.StringBuilder

    sb.Append(_dateOfBirth)
    sb.Append(_notes)
    sb.Append(Name.LastName)
    sb.Append(Name.Preferred)
    sb.Append(Name.Title)
    sb.Append(Name.Forenames)

    Return sb.ToString.GetHashCode()

End Function

, ,

Public Shared Function Compare(ByVal p1 As Person, ByVal p2 As Person) As Boolean

    Return p1.GetHashCode = p2.GetHashCode

End Function

:

object1.GetHashCode = object2.GetHashCode
+2

, , :

AdapdevNet

, , , Reflection Equality, #. VB.NET.

+1

(_Objeto1 _Objeto2). -, . -, (_AnyObject.GetType.ToString). -, . , FALSE. TRUE.

( ). , , ..

Microsoft.VisualBasic System.Reflection

Public Function CompararObjetos (ByVal _Objeto1 As Object, ByVal _Objeto2 As Object) As a logical

    Dim _TipoObjeto1 As String = ""
    Dim _TipoObjeto2 As String = ""

    If Not _Objeto1 Is Nothing Then
        _TipoObjeto1 = _Objeto1.GetType.ToString
    End If

    If Not _Objeto2 Is Nothing Then
        _TipoObjeto2 = _Objeto2.GetType.ToString
    End If

    Dim _Resultado As Boolean = True

    If _TipoObjeto1 = _TipoObjeto2 Then
        Dim Propiedades() As PropertyInfo = _Objeto1.GetType.GetProperties
        Dim Propiedad As PropertyInfo
        Dim _Valor1 As Object
        Dim _Valor2 As Object
        For Each Propiedad In Propiedades
            _Valor1 = Propiedad.GetValue(_Objeto1, Nothing)
            _Valor2 = Propiedad.GetValue(_Objeto2, Nothing)
            If _Valor1 <> _Valor2 Then
                _Resultado = False
                Exit For
            End If
        Next
    Else
        _Resultado = False
    End If

    Return _Resultado

End Function
0
source

I recommend using this NuGet package to compare objects: https://www.nuget.org/packages/CompareNETObjects/

here is the source code: https://github.com/GregFinzer/Compare-Net-Objects

ps I am not associated with it, but used in several projects.

0
source

All Articles