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

2018-01-18  本文已影响17人  蓝色Hippie

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();

        }

    }

}

上一篇 下一篇

猜你喜欢

热点阅读