我需要编写一个比较器来比较各种类型的复杂对象,我写了一些代码,但对我来说似乎太长了,那么有没有其他方法可以很好地比较两个复杂对象?
我的代码:
class CompareObjOfType
{
private static int _totalFalseCount;
public static bool CompareObjectsOfType(Type T, object source, object target)
{
bool result = false;
if ((source == null) && (target == null))
{
return true;
}
if ((source == null) ^ (target == null))
{
_totalFalseCount++;
return false;
}
if (T.IsValueType || (T == typeof(string)))
{
if (T == typeof(DateTime))
{
if (!(((DateTime)source).ToUniversalTime().Equals(((DateTime)target).ToUniversalTime())))
{
_totalFalseCount++;
return false;
}
}
else if (T == typeof(string))
{
if (string.IsNullOrEmpty((string)source) ^ string.IsNullOrEmpty((string)target))
{
_totalFalseCount++;
return false;
}
if (!(string.IsNullOrEmpty((string)source) && string.IsNullOrEmpty((string)target)))
{
_totalFalseCount++;
return false;
}
if (!(((string)source).Equals((string)target)))
{
_totalFalseCount++;
return false;
}
}
else
{
if (!(source.ToString().Equals(target.ToString())))
{
_totalFalseCount++;
return false;
}
}
return true;
}
else
{
var properties = T.GetProperties();
foreach (var property in properties)
{
Type propertyType = property.PropertyType;
if (propertyType.IsArray || propertyType.IsGenericType)
{
var sourceValue = property.GetValue(source);
var targetValue = property.GetValue(target);
if ((sourceValue == null) && (targetValue == null))
{
result = true;
continue;
}
if ((sourceValue == null) ^ (targetValue == null))
{
_totalFalseCount++;
result = false;
continue;
}
var sourceCount = ((IList)sourceValue).Count;
var targetCount = ((IList)targetValue).Count;
if (sourceCount != targetCount)
{
_totalFalseCount++;
result = false;
continue;
}
for (int i = 0; i < sourceCount; i++)
{
Type elementType = propertyType.IsArray
? propertyType.GetElementType()
: propertyType.GetGenericArguments().First();
result = CompareObjectsOfType(elementType, ((IList)sourceValue)[i],
((IList)targetValue)[i]);
}
}
else
{
result = CompareObjectsOfType(propertyType, property.GetValue(source), property.GetValue(target));
}
}
}
return result;
}
}