对比两个实体类属性值的差异

/// <summary>
/// 对比两个实体类属性值的差异
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="oldMod">原实体类</param>
/// <param name="newMod">新实体类</param>
/// <returns>差异记录</returns>
public string GetChangeData<T>(T oldMod, T newMod)
{
Type typeDescription = typeof(DescriptionAttribute);
if (oldMod == null || newMod == null) { return ""; }
string updateData = "";
System.Reflection.PropertyInfo[] mPi = typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

for (int i = 0; i < mPi.Length; i++)
{
System.Reflection.PropertyInfo pi = mPi[i];
object[] arr = pi.GetCustomAttributes(typeDescription, true);
string atrr = arr.Length > 0 ? ((DescriptionAttribute)arr[0]).Description : pi.Name;

object oldObj = pi.GetValue(oldMod, null);
object newObj = pi.GetValue(newMod, null);
string oldValue = oldObj == null ? "" : oldObj.ToString();
string newValue = newObj == null ? "" : newObj.ToString();
if (oldValue != newValue)
{
updateData += atrr + ":由 " + oldValue + " 改成 " + newValue + "<br/>";
}
}
return updateData;
}

原文地址:https://www.cnblogs.com/cxd4321/p/4748412.html