目標:比較類型相同的兩個對象,看看有哪些屬性值發生了變化
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);
}
}