public class CompareHelper
{
/// <summary>
/// 判断两个相同引用类型的对象的属性值是否相等
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj1">对象1</param>
/// <param name="obj2">对象2</param>
/// <param name="type">按type类型中的属性进行比较</param>
/// <returns></returns>
public static void CompareProperties<T>(T obj1, T obj2, ref List<DifferentData> differentDatas)
{
//为空判断
if (obj1 == null || obj2 == null)
return;
Type t = obj1.GetType();
PropertyInfo[] props = t.GetProperties();
foreach (var po in props)
{
if (IsCanCompare(po.PropertyType))
{
object objOld = po.GetValue(obj1);
object objNew = po.GetValue(obj2);
if (objOld != null && objNew != null && !objOld.Equals(objNew))
{
DifferentData differentData = new DifferentData();
differentData.DataName = po.Name;
differentData.OldData = objOld.ToString();
differentData.NewData = objNew.ToString();
differentDatas.Add(differentData);
}
}
else
{
CompareProperties(po.GetValue(obj1), po.GetValue(obj2), ref differentDatas);
}
}
}
/// <summary>
/// 比较不同对象同名成员 嵌套深度必须相同
/// </summary>
/// <typeparam name="TIn1"></typeparam>
/// <typeparam name="TIn2"></typeparam>
/// <param name="oldValue"></param>
/// <param name="newValue"></param>
/// <param name="differentDatas"></param>
/// <returns></returns>
public static void CompareClass<TIn1, TIn2>(TIn1 oldValue, TIn2 newValue, ref List<DifferentData> differentDatas)
{
if (oldValue == null || newValue == null)
return;
Type typeOld = oldValue.GetType();
PropertyInfo[] propertyListOld = typeOld.GetProperties();
Type typeNew = oldValue.GetType();
PropertyInfo[] propertyListNew = typeNew.GetProperties();
foreach (PropertyInfo itemOld in propertyListOld)
{
var itemNew = propertyListNew.FirstOrDefault(x => x.Name == itemOld.Name);
if (itemNew != null)
{
if (IsCanCompare(itemOld.PropertyType) && IsCanCompare(itemNew.PropertyType))
{
object objOld = itemOld.GetValue(oldValue);
object objNew = itemNew.GetValue(newValue);
if (objOld != null && objNew != null && !objOld.Equals(objNew))
{
DifferentData differentData = new DifferentData();
differentData.DataName = typeOld.Name + "." + itemOld.Name;
differentData.OldData = objOld.ToString();
differentData.NewData = objNew.ToString();
differentDatas.Add(differentData);
}
}
else
{
CompareClass(itemOld.GetValue(oldValue), itemNew.GetValue(newValue), ref differentDatas);
}
}
}
}
/// <summary>
/// 该类型是否可直接进行值的比较
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private static bool IsCanCompare(Type t)
{
if (t.IsValueType || t.FullName == typeof(string).FullName || t.IsPrimitive || t.IsEnum || t.Equals(typeof(DateTime)))
{
return true;
}
else
{
return false;
}
}
}
public class DifferentData
{
public string DataName { get; set; }
public string OldData { get; set; }
public string NewData { get; set; }
}