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

本文介绍了一种用于比较两个实体类属性值差异的方法,并提供了一个具体的实现案例。该方法通过反射获取实体类的所有公共属性,然后逐个比较这些属性在两个实体间的值是否相同。如果发现不同,则记录下具体的变更内容。

/// <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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值