代码:比较两个类型相同的对象所有属性是否相等

    [TestFixture]
    public class CompareHelperTest
    {
        private class C
        {
            public String P1 { get; set; }
            public Int32 P2 { get; set; }
        }

        [Test]
        public void testPropertiesEqual()
        {
            C c1 = new C();
            c1.P1 = "a";
            c1.P2 = 5;

            C c2 = new C();
            c2.P1 = "a";
            c2.P2 = 5;

            Assert.IsTrue(CompareHelper.PropertiesEqual(c1, c2));

            c2.P2 = 6;
            Assert.IsFalse(CompareHelper.PropertiesEqual(c1, c2));
            c2.P2 = 5;

            c2.P1 = "A";
            Assert.IsFalse(CompareHelper.PropertiesEqual(c1, c2));
            c2.P1 = "a";

        }
    }

    public static class CompareHelper
    {
        /// <summary>
        /// 比较两个对象的所有可读属性是否相等。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static bool PropertiesEqual<T>(T a, T b)
        {
            Type t = typeof(T);

            foreach (System.Reflection.PropertyInfo pi in t.GetProperties())
            {
                if (!pi.CanRead)
                {
                    continue;
                }
                if (!Object.Equals(pi.GetValue(a, null), pi.GetValue(b, null)))
                {
                    return false;
                }
            }

            return true;
        }
    }

  

posted @ 2012-05-21 16:48  梦幻泡影  阅读(345)  评论(0编辑  收藏  举报