C#中在比较自定义对象的时候要重写Equals方法

using System;
using System.Collections.Generic;
using System.Text;

namespace Equal
{
    using System;

    class Test
    {
        public static void Main()
        {
            Person p1 = new Person("A", 1);
            Person p2 = new Person("A", 1);          

            if (p1.Equals (p2))
            {
                Console.WriteLine("true");
            }
            else
            {
                Console.WriteLine("false");
            }
        }


    }
    class Person
    {
        private string name;
        private int age;

        public Person()
        {
            this.name = "";
            this.age = 0;
        }
        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        //重写Equals方法

        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return false;
            }
            if ((obj.GetType().Equals(this.GetType())) == false)
            {
                return false;
            }
            Person temp = null;
            temp = (Person)obj;

            return this.name.Equals(temp.name) && this.age.Equals(temp.age);

        }

        //重写GetHashCode方法(重写Equals方法必须重写GetHashCode方法,否则发生警告

        public override int GetHashCode()
        {
            return this.name.GetHashCode() + this.age.GetHashCode();
        }
    }

}

posted @ 2017-02-15 16:37  米其林5212  阅读(4101)  评论(0编辑  收藏  举报