博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

参照网上代码 获取两个对象的差异。

Posted on 2017-09-11 14:20  生命如风  阅读(210)  评论(0编辑  收藏  举报

参考代码



static
class extentions { public static List<Variance> Diff<T>(this T val1, T val2) { List<Variance> variances = new List<Variance>(); var propertyInfo = val1.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var item in propertyInfo) { var attr = item.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault(); ///不设置描述的不进行对比记录 if (attr != null) { string description = ((DescriptionAttribute)attr).Description; string propCode = item.Name; object originalValue = item.GetValue(val1,null); object newValue = item.GetValue(val2,null); if (Convert.ToString(originalValue) != Convert.ToString(newValue)) { variances.Add ( new Variance() { PropCode = propCode, NewValue = Convert.ToString(newValue), OriginalValue = Convert.ToString(originalValue), PropDescription = description } ); } } } return variances; } } public class Variance { /// <summary> /// 字段名 /// </summary> public string PropCode { get; set; } /// <summary> /// 字段描述 /// </summary> public string PropDescription { get; set; } /// <summary> /// 修改之前 /// </summary> public string OriginalValue { get; set; } /// <summary> /// 修改之后 /// </summary> public string NewValue { get; set; } }