.NET 对比两个对象是否发生变化


/// <summary>
/// 获取两个对象间的值发生变化的描述
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="obj1">变化前的对象</param>
/// <param name="obj2">变化后的对象</param>
/// <param name="isDes">是否过滤掉没有[Description]标记的</param>
/// <returns>字符串</returns>
public static List<ChangeItems> GetObjCompareString<T>(T obj1, T obj2, bool isDes) where T : new()
{
string res = string.Empty;
List<ChangeItems> list = new List<ChangeItems>();

if (obj1 == null || obj2 == null)
{
return null;
}
var properties =
from property in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
select property;

string objVal1 = string.Empty;
string objVal2 = string.Empty;

foreach (var property in properties)
{
var ingoreCompare = Attribute.GetCustomAttribute(property, typeof(IngoreCompareAttribute));
if (ingoreCompare != null)
{
continue;
}
objVal1 = property.GetValue(obj1, null) == null ? string.Empty : property.GetValue(obj1, null).ToString();
objVal2 = property.GetValue(obj2, null) == null ? string.Empty : property.GetValue(obj2, null).ToString();

string des = string.Empty;
DescriptionAttribute descriptionAttribute = ((DescriptionAttribute)Attribute.GetCustomAttribute(property, typeof(DescriptionAttribute)));
if (descriptionAttribute != null)
{
des = ((DescriptionAttribute)Attribute.GetCustomAttribute(property, typeof(DescriptionAttribute))).Description;// 属性值
}
if (isDes && descriptionAttribute == null)
{
continue;
}
if (!objVal1.Equals(objVal2))
{
ChangeItems change = new ChangeItems();
change.changeItem = string.IsNullOrEmpty(des) ? property.Name : des;
if (change.changeItem == "集中器")
{
objVal1 = GetDeviceName(objVal1);
objVal2 = GetDeviceName(objVal2);
}
change.beforeChange = objVal1;
change.afterChange = objVal2;

list.Add(change);
//arrayList.Add(new
//{
// changeItem = string.IsNullOrEmpty(des) ? property.Name : des,
// beforeChange = objVal1,
// afterChange = objVal2
//});
//res += (string.IsNullOrEmpty(des) ? property.Name : des) + ":" + objVal1 + "->" + objVal2 + "; ";
}

}
return list;
}

/// <summary>
/// 加入些特性后,在实体差异比较中会忽略该属性
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class IngoreCompareAttribute : Attribute
{
public IngoreCompareAttribute()
{
Flag = true;
}

public bool Flag { get; set; }
}

public class ChangeItems
{
public string changeItem { get; set; }
public string beforeChange { get; set; }
public string afterChange { get; set; }
}

posted on 2018-12-04 17:21  随,风  阅读(209)  评论(0编辑  收藏  举报

导航