常常,咱們會遇到一個場景,在保存對象到數據庫以前,對比內存對象和數據庫值的差別。
下面我寫了一種實現,爲保存定義一個事件,而後自動找出對象之間的差別,請注意,並無經過反射的方式去獲取每一個屬性及其值。由於那樣會影響性能。
閒話不表,直接貼代碼數據庫
class Program { static void Main(string[] args) { Staff s = new Staff("10000", "11111", "22222"); StaffOM.Save(s); Console.ReadLine(); } } public class Staff { public string StaffNo { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Staff(string no, string fn, string ln) { StaffNo = no; FirstName = fn; LastName = ln; } public static IList<ObjectDifference> GetDifferences(Staff x, Staff y) { return new List<ObjectDifference> { new ObjectDifference("FirstName", x.FirstName, y.FirstName), new ObjectDifference("LastName", x.LastName, y.LastName) }; } } public static class StaffOM { public static void Save(Staff s) { StaffDAO.OnSave += StaffDAO_OnSave; StaffDAO.Save(s); } public static void StaffDAO_OnSave(Staff s) { Staff old = new Staff("10000", "AAA", "BBB"); string result = ObjectHelper.FindDifference(()=>Staff.GetDifferences(old,s)); Console.WriteLine(result); } } public delegate void StaffSaveHandler(Staff s1); public static class StaffDAO { public static void Save(Staff s) { OnSave(s); } public static event StaffSaveHandler OnSave; } public static class ObjectHelper { public static string FindDifference(Func<IList<ObjectDifference>> func) { StringBuilder buffer = new StringBuilder(); foreach (ObjectDifference objDiff in func()) buffer.Append(objDiff.ToString()); return buffer.ToString(); } } public class ObjectDifference { public string PropertyName { get; set; } public string OldValue { get; set; } public string NewValue { get; set; } public ObjectDifference(string p, string o, string n) { PropertyName = p; OldValue = o; NewValue = n; } public override string ToString() { return string.Format("{0}: {1} -> {2}\n", PropertyName, OldValue, NewValue); } }