Vb.net 强制执行.Equals重写必须比较新添加的属性

Vb.net 强制执行.Equals重写必须比较新添加的属性,vb.net,Vb.net,我有一个覆盖等于的类。此类有许多属性,将来将添加更多属性。如何执行,当添加新属性时,等于必须改变重写以考虑这些属性? 我有一个局部解决方案,所以你可以看到我正在尝试做什么: Public Class LotsOfProperties Public Shared ReadOnly properties As New HashSet(Of String) From {"propertyA", "propertyB"} Public Property propertyA As Str

我有一个覆盖
等于
的类。此类有许多属性,将来将添加更多属性。如何执行,当添加新属性时,<代码>等于必须改变重写以考虑这些属性?

我有一个局部解决方案,所以你可以看到我正在尝试做什么:

Public Class LotsOfProperties
    Public Shared ReadOnly properties As New HashSet(Of String) From {"propertyA", "propertyB"}

    Public Property propertyA As String
    Public Property propertyB As List(Of String)

    Public Overloads Function Equals(ByVal otherObj As LotsOfProperties) As Boolean
        Dim differences As New List(Of String)

        For Each propertyName As String In properties
            Dim meValue As Object = getValueByPropertyName(Me, propertyName)
            Dim otherObjValue As Object = getValueByPropertyName(otherObj, propertyName)
            If Not meValue.Equals(otherObjValue) Then
                differences.Add(propertyName)
            End If
        Next

        Return (differences.Count = 0)

    End Function

    Private Function getValueByPropertyName(ByVal obj As Object, ByVal name As String) As Object
        Dim rtnObj As Object
        Dim pInfo As Reflection.PropertyInfo = obj.GetType.GetProperty(name)
        rtnObj = pInfo.GetValue(obj, Reflection.BindingFlags.GetProperty, Nothing, Nothing, Nothing)
        Return rtnObj
    End Function
End Class
但是,这不起作用,因为我想使用SequenceEqual来比较List属性,而不是比较String属性。因为我必须使用不同的方法来测试每个属性的相等性,所以我不能仅仅通过反射循环属性


这似乎是一个常见的用例。是否有一个简单的解决方案,或者我需要简单地相信未来的开发人员在添加新属性时会修改
Equals

您的代码是否有任何类型的测试?您可以编写一个使用反射并验证您的条件的测试。@MarcinJuraszek我仍然有一个基本问题,即检测
Equals
方法中是否使用了该属性。如何使用反射检查属性是否在特定方法中被访问?这似乎是一个过程问题,而不是代码问题。@Jack您不必检查代码。检查行为。创建类的两个实例,将两个实例中的所有属性设置为相同的值,但一个属性除外。调用
等于
。如果返回false,则该属性用于确定相等性。如果它返回
true
,则不是。啊,这是有道理的!所以在测试中,我应该创建两个对象,使它们在一个属性上有所不同,然后测试
Equals
是否返回
false
?问题是,我有不同的属性类型,所以想出两个单独的默认值将是棘手的。你有解决那个问题的办法吗?谢谢你的帮助!