110,499
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 将两个同样的对象对比,针对不同的值进行新旧值的拼接,返回拼接后的字符串
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="oldModel">旧对象</param>
/// <param name="newModel">新对象</param>
/// <param name="appointRecordStrs">指定需要记录的字段集合,主要目的是为了日志查看方便。
/// 设置的字段无论新旧对象的值是否变更,均记录该字段的值。大小写要保持和类的属性一致</param>
/// <param name="existsStrs">需要排除记录的字段,例如创建时间、更新时间等,大小写要保持和类的属性一致</param>
/// <returns>拼接后的字符串</returns>
public string ConvertClassDifferentToString<T>(T oldModel, T newModel, string[] appointRecordStrs = null, string[] existsStrs = null)
{
bool isChange = false;
StringBuilder sb = new StringBuilder();
PropertyInfo[] PropertyList = oldModel.GetType().GetProperties();
foreach (PropertyInfo item in PropertyList)
{
if (existsStrs != null && existsStrs.Count() > 0 && existsStrs.Contains(item.Name))
{
continue;
}
object oldValue = item.GetValue(oldModel, null);
object newValue = item.GetValue(newModel, null);
var deso = Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute));
string des = "";
if (deso != null)
{
des = ((DescriptionAttribute)deso).Description;
}
if (!Equals(oldValue, newValue))
{
isChange = true;
sb.AppendFormat("属性{0}的原值:{1}、现值:{2},", !string.IsNullOrEmpty(des) ? des : item.Name, oldValue == null ? "" : oldValue.ToString(), newValue == null ? "" : newValue.ToString());
}
else if (appointRecordStrs != null && appointRecordStrs.Count() > 0 && appointRecordStrs.Contains(item.Name))
{
sb.AppendFormat("属性{0}的值:{1},", !string.IsNullOrEmpty(des) ? des : item.Name, oldValue == null ? "" : oldValue.ToString());
}
}
if (!isChange)
{
sb.Append("本次编辑未变更任何数据。");
}
return sb.ToString().TrimEnd(',');
}