码迷,mamicode.com
首页 > Windows程序 > 详细

C# Equals的重写

时间:2016-09-23 18:17:58      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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

}

C# Equals的重写

标签:

原文地址:http://www.cnblogs.com/hlws/p/5900868.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!