2011-01-12 144 views
2

我正在使用外部庫,它返回對象的舊狀態和當前狀態(其中數組中的每個項表示屬性及其值)的對象數組。到目前爲止,我已經拿出了:遞歸比較兩個對象數組

for(var i = 0; i < oldState.Length; i ++){ return oldState [i] .Equals(state [i]); }

這比較了所有頂級屬性。但是我也希望鑽入一些(用CompareComplex屬性標記的)複雜屬性,並比較它們之間的差異。我會想象得到這個的最好方法是使用遞歸函數。我無法理解這一點,但我確信解決方案非常簡單。

我真的很感激,如果有人可以幫忙。謝謝

+0

可能是重複的http://stackoverflow.com/questions/1539989/c-實施 - 關 - 遞歸 - 對象 - 比較 - in-net-3-5 – BrokenGlass

+0

以前也有類似的問題,請參閱http://stackoverflow.com/questions/1539989/c-implementation-of-deep-recursive-object-comparison-in-net-3-5 –

回答

0

歡呼你的答案我已成功地拿出了以下方法:

private bool Compare(Type type, string[] propertyNames, object[] oldState, object[] state) { 
    // Get the property indexes to ignore 
    var propertyIndexesToIgnore = type.GetProperties() 
     .Where(p => p.GetCustomAttributes(typeof(IgnoreLoggingAttribute), false).Count() > 0) 
     .Select(p => Array.IndexOf(propertyNames, p.Name)).ToArray(); 

    // Get the child property indexes 
    var childPropertyIndexes = type.GetProperties() 
     .Where(p => p.GetCustomAttributes(typeof(ChildLoggingAttribute), false).Count() > 0) 
     .Select(p => Array.IndexOf(propertyNames, p.Name)).ToArray(); 

    for (var i = 0; i < oldState.Length; i++) { 
     // If we need to check the child properties 
     if (childPropertyIndexes.Contains(i)) { 
      if (oldState[i] == null) 
       break; 

      var childPropertyType = oldState[i].GetType(); 
      var childProperties = oldState[i].GetType().GetProperties(); 

      // Recursively call this function to check the child properties 
      if (Compare(childPropertyType, childProperties.Select(p => p.Name).ToArray(), childProperties.Select(p => p.GetValue(oldState[i], null)).ToArray<object>(), childProperties.Select(p => p.GetValue(state[i], null)).ToArray<object>())) 
       return true; 
     } else if (!propertyIndexesToIgnore.Contains(i) && ((oldState[i] != null && state[i] != null && !oldState[i].Equals(state[i])) || (oldState[i] != null && state[i] == null) || (oldState[i] == null && state[i] != null))) 
      return true; 
    } 

    return false; 
} 

有幾件事情需要注意:

  1. 性能在我最初的對象數組金額不匹配type.GetProperties()中的項目數。我看不出如何說對象數組中的對象是否具有IgnoreLogging屬性,因此我將它與類型進行比較。
  2. ChildLoggingAttribute用於確定何時屬性是複雜類型。

如果有人對我如何改善這一點有任何建議,那麼我會非常感激。謝謝

2

你的代碼只比較第一個元素!

更好:

return oldState.SequenceEquals(state); 

要做到 「深比較」 覆蓋 「狀態」 類的Equals()方法。

0

承擔迭代可能的方法是:

  • 爲你寫的比較單對對象(oldObjectobject)你怎麼代碼
  • 複製測試進入循環

    for (var i = 0; i < oldState.Length; i++) 
    { 
        ObjectType oldObject = oldState[i]; 
        ObjectType object= state[i]; 
    
        \\insert your comparison code here 
        oldObject.Property.Equals(object.Property); 
    } 
    
    01:以及運行比較代碼

像之前設置的對象在

重要的是,取出該return語句,以便在i == 0的迭代後不會停止執行,並將結果保留在另一個對象中。