我有一个覆盖Equals
的课程。此类具有许多属性,将来会添加更多属性。如何强制执行此操作,添加新属性时,必须更改Equals
覆盖以考虑这些属性?
我有一个部分解决方案,所以你可以看到我正在尝试做的事情:
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
?