我需要将数据库中当前的对象列表与新的对象列表进行比较。我想比较它们并为用户突出显示已更改的内容(在这种情况下,返回TRUE它们是不同的)。
由于我的一些对象是Nullable,这涉及到很多IF并不是NewObj和CurrentObj的一面......我试图找到一种更有效的方式来编写下面的内容,因为我必须用它来比较不同类型的30个对象,IE Date,Decimal,Int等。
以下内容有效,直到Obj中没有任何一个没有Rank,因此没有
建议?
Dim Rank As Boolean = CompareData(NewObj, CurrentObj, "Rank")
Dim Regiment As Boolean = CompareData(NewObj, CurrentObj, "Rank")
Dim DateofBirth As Boolean = CompareData(NewObj, CurrentObj, "DoB")
Private Function CompareData(NewObj As Business.Casualty, CurrentObj As Business.Casualty, FieldToComapre As String) As Boolean
Select Case FieldToComapre
Case "DateOfBirth"
Return (Nullable.Equals(NewCasualty.DateOfBirth, CurrentCasualty.DateOfBirth))
Case "Age"
Return (Nullable.Equals(NewCasualty.Age, CurrentCasualty.Age))
Case "Rank"
Return (Nullable.Equals(NewCasualty.Rank.ID, CurrentCasualty.Rank.ID))
Case "Regiment"
Return (Nullable.Equals(NewCasualty.Regiment.ID, CurrentCasualty.Regiment.ID))
Case Else
Return True
End Select
End Function
答案 0 :(得分:0)
我的第一个建议是将函数的名称更改为类似AreFieldValuesTheSame的名称。我的第二个建议是否定该功能的目的。换句话说,当值相同时返回True。
如果你按照我的前两个建议,那么对于你的每一个案例,而不是简单的
Return (Nullable.Equals(a.ID, b.ID))
你需要更像
的东西Return ((a Is Nothing And b Is Nothing) Or (a.ID Is Nothing And b.ID Is Nothing) Or (Nullable.Equals(a.ID, b.ID)))
例如,a代表NewCasualty.Rank,b代表CurrentCasualty.Rank。在尝试检查对象的属性之前,需要检查对象是否为Nothing(换句话说为null)。
此外,在函数的开头,您需要检查NewObj是否为Nothing以及CurrentObj是否为Nothing:
If (NewObj Is Nothing) And (CurrentObj Is Nothing) Then
Return True
Else If (NewObj Is Nothing) Or (CurrentObj Is Nothing)
Return False
如果我的VB语法不完美,请原谅我。 (我对C#更加流利。)
答案 1 :(得分:0)
我实际上最终只是使用扩展方法..这是更简单和更清洁的IMO。
Dim Rank As Boolean = CompareData(NewObj, CurrentObj, "Rank")
Dim Regiment As Boolean = CompareData(NewObj, CurrentObj, "Regiment")
Dim Trade As Boolean = CompareData(NewObj, CurrentObj, "Trade")
Private Function CompareData(NewObj As Business.Casualty, CurrentObj As Business.Casualty, FieldToComapre As String) As Boolean
Select Case FieldToComapre
Case "Trade"
Return NewCasualty.Trade.NullableEquals(CurrentCasualty.Trade)
Case "Rank"
Return NewCasualty.Rank.NullableEquals(CurrentCasualty.Rank)
Case "Regiment"
Return NewCasualty.Regiment.NullableEquals(CurrentCasualty.Regiment)
Case Else
Return True
End Select
End Function
public static class NullableCompare
{
public static bool NullableEquals<T>(this T s1, T s2)
where T : class
{
if (s1 == null)
{
return s2 == null;
}
return s1.Equals(s2);
}
}
public partial class Rank
{
public override bool Equals(object obj)
{
var p2 = obj as Rank;
if (p2 == null)
{
return false;
}
if (this.ID != p2.ID)
{
return false;
}
return this.ID == p2.ID;
}
public override int GetHashCode()
{
return this.ID.GetHashCode();
}
}