C#记录对象的变化

经常,我们会遇到一个场景,在保存对象到数据库之前,对比内存对象和数据库值的差异。

下面我写了一种实现,为保存定义一个事件,然后自动找出对象之间的差异,请注意,并没有通过反射的方式去获取每个属性及其值。因为那样会影响性能。

闲话不表,直接贴代码

 

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);
        }
    }
All code

 

posted @ 2014-02-21 17:36  On the road....  阅读(772)  评论(0编辑  收藏  举报