比较两个对象是否相等

来源:互联网 发布:php function use as 编辑:程序博客网 时间:2024/05/30 05:10
using System;using System.Collections.Generic;using System.Text;using System.Reflection;namespace ObjectCompare{    public class Person    {        public string Name { get; set; }        public int Age { get; set; }    }    static class Program    {        static void Main(string[] args)        {            CompareObjectTest();        }        /// <summary>        /// 测试方法        /// </summary>        public static void CompareObjectTest()        {            Person FirstPerson = new Person() { Name = "张三", Age = 20 };            Person SecondPerson = new Person() { Name = "张三", Age = 21 };            bool flag = FirstPerson.ToString().Equals(SecondPerson.ToString());            Console.WriteLine(flag);            bool actua = FirstPerson.CompareWith(SecondPerson);            Console.WriteLine(actua);            Console.Read();        }        /// <summary>        /// 将对象序列化为字符串        /// </summary>        /// <param name="obj"></param>        /// <returns></returns>        public static string Serialize(this object obj)        {            if (null == obj)                return string.Empty;            Type type = obj.GetType();            FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);            StringBuilder objString = new StringBuilder();            foreach (FieldInfo field in fields)            {                objString.Append(field.Name + ":");                object value = field.GetValue(obj);     //取得字段的值                if (null != value)                {                    Type filedType = value.GetType();                    //判断该字段类型是否为类,且不是string类型                    if (filedType.IsClass && "String" != filedType.Name)                        objString.Append(Serialize(value));                    objString.Append(value);                }                objString.Append(";");            }            return objString.ToString();        }        /// <summary>        /// 比较两个对象是否相等        /// </summary>        /// <param name="obj1"></param>        /// <param name="obj2"></param>        /// <returns></returns>        public static bool CompareWith(this object obj1, object obj2)        {            if (null == obj1 || null == obj2)                return false;            if (obj1.GetType() != obj2.GetType())                return false;            return obj1.Serialize().Equals(obj2.Serialize());        }    }}

原创粉丝点击