目标:比较类型相同的两个对象,看看有哪些属性值发生了变化
class static MyExtension
{
//参数oldObject 原始对象, 参数newObject新对象
//compareProperties 需要比较的属性(t => t.Name, t => t.Id, ...)
public static string GetModifyRemark<T>(thisT oldObject, T newObject,paramsExpression<Func<T, object>>[] compareProperties)
{
stringspliter = "";
StringBuilder sb= newStringBuilder();
foreach (var property in compareProperties)
{
if (property == null) continue;
//将输入的表达式转换成成员表达式
MemberExpression body = property.Body as MemberExpression;
if (body == null)
{
//如果表达式不是成员表达式,则转换成一元表达式
UnaryExpression temp = property.Body asUnaryExpression;
if (temp != null)
//将一元表达式的Operand 转换成成员表达式
body = temp.Operand as MemberExpression;
}
if(body == null)
throw new System.Exception(string.Format("Error Expression:{0}!", property));
//根据属性名获取属性信息对象,如果该属性不可读,则转向下一循环
PropertyInfo pi = typeof(T).GetProperty(body.Member.Name);
if (pi.CanRead == false)
continue;
//获取两个对象在指定属性上的值
object oldProperyValue = pi.GetValue(oldObject, null);
object newProperyValue = pi.GetValue(newObject, null);
if (Compare(oldProperyValue, newProperyValue) == false)
{
sb.AppendFormat("{2}{3} from {0} to {1}", oldProperyValue, newProperyValue, spliter, body.Member.Name);
spliter = ", ";
}
}
return sb.ToString();
}
private static bool Compare(object objA, object objB)
{
int result = 0;
//判断两个对象是否可以直接比较
if (objA is IComparable)
{
result = ((IComparable)objA).CompareTo(objB);
}
else
result = objA.ToString().CompareTo(objB.ToString());
return result == 0;
}
}
class Student
{
public stringName{get; set;}
public int Age{get; set;}
public string Sex{get; set;}
}
public class Program
{
public static void Main()
{
Student s1 = new Student (){Name = "zs", Age = 11, Sex = "Male"};
Student s2 = new Student (){Name = "zs", Age = 12, Sex = "FeMale"};
string result = s1.GetModifyRemark(s2, s => s.Age, s => s.Sex);
Console.WriteLine(result);
}
}