歡呼你的答案我已成功地拿出了以下方法:
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;
}
有幾件事情需要注意:
- 性能在我最初的對象數組金額不匹配type.GetProperties()中的項目數。我看不出如何說對象數組中的對象是否具有IgnoreLogging屬性,因此我將它與類型進行比較。
- ChildLoggingAttribute用於確定何時屬性是複雜類型。
如果有人對我如何改善這一點有任何建議,那麼我會非常感激。謝謝
可能是重複的http://stackoverflow.com/questions/1539989/c-實施 - 關 - 遞歸 - 對象 - 比較 - in-net-3-5 – BrokenGlass
以前也有類似的問題,請參閱http://stackoverflow.com/questions/1539989/c-implementation-of-deep-recursive-object-comparison-in-net-3-5 –