GetHashCode的和等于实施字典C# [英] GetHashCode and Equals implementation in Dictionary C#

查看:113
本文介绍了GetHashCode的和等于实施字典C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来到这个网站寻找在Dictionary对象比较,我才知道,压倒一切的GetHashCode和equals是在C#中做对象比较是必须的。
下面是一段代码,我一直在试图解决掉,使用foreach迭代方法。但我的老板说做同样不使用任何迭代(也许用的containsKey或containsvalue和方法),由于性能问题。任何帮助是非常值得欢迎的。



 公共类员工
{
公共字符串empname {搞定;组; }
公共字符串位置{搞定;组; }
公共双kinid {搞定;组; }
公共双managerKin {搞定;组; }
公众覆盖布尔等于(obj对象)
{
返回base.Equals(OBJ);
}
公共覆盖INT的GetHashCode()
{
返回base.GetHashCode();
}
}

公共类经理
{
公共字符串managername {搞定;组; }
公共双kinid {搞定;组; }

公共覆盖INT的GetHashCode()
{
返回17 * managername.GetHashCode()+ kinid.GetHashCode();
}
}
公共类节目
{
公共静态无效的主要()
{
员工EMP =新员工();
员工EMP2 =新员工();
经理MNG =新经理();
经理mng2 =新经理();

emp.empname =迪派;
emp.location =普纳;
emp.kinid = 36885;
emp.managerKin = 007;


emp2.​​empname =Astha;
emp2.​​location =普纳;
emp2.​​kinid = 30000;
emp2.​​managerKin = 007;

mng.kinid = 007;
mng.managername =拉夫;
mng2.kinid = 001;
mng2.managername =苏里亚;

&字典LT,员工,经理>关系=新词典<员工,经理>();
relations.Add(EMP,MNG);
relations.Add(EMP2,mng2);

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(经理细节是:);
的foreach(在关系VAR元素)
Console.WriteLine(\\\
KINID:{0} \\\
Manager'sName:{1},element.Value.kinid,element.Value。 managername);
Console.WriteLine(输入管理器的细节。);
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(\\\
Manager的健:);
双mkin = Convert.ToDouble(到Console.ReadLine());

Console.Write(经理的名字:);
字符串MNAME =到Console.ReadLine();

经理mng1 =新经理();
mng1.kinid = mkin;
mng1.managername = MNAME;
INT散列值= 17 * mname.GetHashCode()+ mkin.GetHashCode();



#地区若使用foreach循环
INT I = 0;
的foreach(在关系VAR元素)
{
如果(element.Value.GetHashCode()==散列值)
{
I + = 1;
如果(我== 1)
{
Console.WriteLine(以下员工的经理汇报:{0},MNAME);

}
Console.WriteLine(element.Key.empname ++ element.Key.kinid ++ element.Key.location ++ element.Key.managerKin) ;

}
}
如果(我== 0)
{
Console.WriteLine(对不起经理的详细信息您输入\{0 } \\{1} \并不在我们的数据库中。,mng1.managername,mng1.kinid);

}
#endregion

到Console.ReadLine();
}

}


解决方案

对于使用的containsKey或关键字的containsValue字典搜索对象时,编译器将使用两个隐含的职能,即GetHashCode()方法和equals()。所以,当我们有比较的对象,我们需要重写这两种方法!



下面是代码



 #地区使用字典来存储类对象(检查员工的存在和打印管理器的名称)
公共类员工
{
公共字符串empname {搞定;组; }
公共字符串位置{搞定;组; }
公共双kinid {搞定;组; }
公共双managerKin {搞定;组; }

//公共覆盖布尔等于(obj对象)//任何两个equals方法的作品。
// {
//员工otheremployee;
// otheremployee =(员工)目标文件;
//返回(otheremployee.kinid == this.kinid&放大器;&安培; otheremployee.location == this.location&放大器;&安培; otheremployee.empname == this.empname&放大器;&安培; otheremployee.managerKin ==这.managerKin);

//}
公众覆盖布尔等于(obj对象)//当运行这个整个代码,把一个破发点上都等于()和GetHashCode()方法,看执行流程。
{
员工otheremployee;
otheremployee =(员工)目标文件;
返回(obj.GetHashCode()== otheremployee.GetHashCode());

}
公共覆盖INT的GetHashCode()//当运行这个整个代码,把双方的equals()和GetHashCode()方法断点,并查看执行流程。
{
// INT TEMP = base.GetHashCode(); //请勿使用此
//返回base.GetHashCode();
INT TEMP = empname.GetHashCode()+ location.GetHashCode()+ kinid.GetHashCode()+ managerKin.GetHashCode();
返回温度;
}
}

公共类经理
{
公共字符串managername {搞定;组; }
公共双kinid {搞定;组; }



公共覆盖INT的GetHashCode()
{
返回base.GetHashCode();
}
公众覆盖布尔等于(obj对象)
{
返回base.Equals(OBJ);
}
}
公共类节目
{
公共静态无效的主要()
{
员工EMP =新员工();
员工EMP2 =新员工();
经理MNG =新经理();
经理mng2 =新经理();

emp.empname =迪派;
emp.location =普纳;
emp.kinid = 36885;
emp.managerKin = 007;


emp2.​​empname =Astha;
emp2.​​location =普纳;
emp2.​​kinid = 30000;
emp2.​​managerKin = 001;

mng.kinid = 007;
mng.managername =拉夫;
mng2.kinid = 001;
mng2.managername =苏里亚;

&字典LT,员工,经理>关系=新词典<员工,经理>();
relations.Add(EMP,MNG); //这里放一个断点,并查看执行流程
relations.Add(EMP2,mng2); //将断点这里,看看执行流程

Console.ForegroundColor = ConsoleColor.Yellow ;
Console.WriteLine(该员工细节是:);
的foreach(在关系VAR元素)
Console.WriteLine(\\\
雇员姓名:{0} \\\
地点:{1} \\\
员工KinId:{2} \\\
经理KinId:{3},
element.Key.empname,element.Key.location,element.Key.kinid,element.Key.managerKin);

Console.WriteLine(请输入员工的详细信息。);
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(\\\
Employee名称:);字符串的ename =到Console.ReadLine();
Console.Write(位置:);字符串elocn =到Console.ReadLine();
Console.Write(员工KinId:);双ekinid = Convert.ToDouble(到Console.ReadLine());
Console.Write(经理ID:);双emngr = Convert.ToDouble(到Console.ReadLine());
员工EMP1 =新员工();
emp1.empname =为ename;
emp1.location = elocn;
emp1.kinid = ekinid;
emp1.managerKin = emngr;


INT I = 0; //该变量用作指示器,找到雇员密钥是否存在。
如果(relations.ContainsKey(EMP1))//此处将一个破发点,看到了执行流程。
{
Console.WriteLine(雇员:{0}存在..,emp1.empname);
Console.WriteLine(员工报告以下管理员:{0} \\\
和经理的KinId为{1},(关系[EMP1])managername,关系[EMP1] .kinid) ;
I = 1;
到Console.ReadLine();
}

如果(我== 0)
{
Console.WriteLine(员工命名的细节{0}不存在! emp1.empname);
到Console.ReadLine();
}

#endregion


I came to this site searching for object comparison in Dictionary, and i came to know that overriding GetHashCode and Equals are a must for doing object comparison in C#. Here is a piece of code that i have been trying to solve out, using FOREACH iteration Method. But my Boss says to do the same without using any iteration(maybe by using containskey or containsvalue method), due to performance issues. Any help is highly welcome..

  public class employee
    {
        public string empname { get; set; }
        public string location { get; set; }
        public double kinid { get; set; }
        public double managerKin { get; set; }
        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }

    public class manager
    {
        public string managername { get; set; }
        public double kinid { get; set; }

        public override int GetHashCode() 
        { 
          return 17 * managername.GetHashCode() + kinid.GetHashCode();
        }
    }
    public class program
    {
        public static void Main()
        {
            employee emp = new employee();
            employee emp2 = new employee();
            manager mng = new manager();
            manager mng2 = new manager();

            emp.empname = "Deepak";
            emp.location = "Pune";
            emp.kinid = 36885;
            emp.managerKin = 007;


            emp2.empname = "Astha";
            emp2.location = "Pune";
            emp2.kinid = 30000;
            emp2.managerKin = 007;

            mng.kinid = 007;
            mng.managername = "Gaurav";
            mng2.kinid = 001;
            mng2.managername = "Surya";

            Dictionary<employee, manager> relations = new Dictionary<employee, manager>();
            relations.Add(emp, mng);
            relations.Add(emp2, mng2);

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("The Manager details are :");
            foreach (var element in relations)
            Console.WriteLine(" \n KINID : {0} \n  Manager'sName :                    {1}",element.Value.kinid, element.Value.managername);
            Console.WriteLine("Enter the details of the manager..");
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.Write("\nManager's Kin : ");
            double mkin = Convert.ToDouble(Console.ReadLine());

            Console.Write("Manager's Name : ");
            string mname = Console.ReadLine();

            manager mng1 = new manager();
            mng1.kinid = mkin;
            mng1.managername = mname;
            int hashvalue = 17 * mname.GetHashCode() + mkin.GetHashCode();



            #region BY USING FOREACH LOOP
            int i = 0;
            foreach (var element in relations)
            {
                if (element.Value.GetHashCode() == hashvalue)
                {
                    i += 1;
                    if (i == 1)
                    {
                        Console.WriteLine("The Following employees report to the Manager : {0}", mname);

                    }
                    Console.WriteLine(element.Key.empname + " " + element.Key.kinid + " " + element.Key.location + " " + element.Key.managerKin);

                }
            }
            if (i == 0)
            {
                Console.WriteLine("sorry the manager's details you entered \"{0}\" \"{1}\" does not exist in our database..", mng1.managername, mng1.kinid);

            }
            #endregion

            Console.ReadLine();
        }

    }

解决方案

For searching an object in a dictionary using the ContainsKey or ContainsValue keyword, compiler uses two implicit functions i.e. GetHashCode() and Equals(). So when we have an object for comparison, we need to Override both these methods !!

Here is the code

#region USING DICTIONARY TO STORE CLASS OBJECTS (check employee existence and print manager's name)
public class employee
{
    public string empname { get; set; }
    public string location { get; set; }
    public double kinid { get; set; }
    public double managerKin { get; set; }

    //public override bool Equals(object obj) // ANY OF THE TWO EQUALS METHOD WORKS.
    //{
    //    employee otheremployee;
    //    otheremployee = (employee)obj;
    //    return (otheremployee.kinid == this.kinid && otheremployee.location == this.location && otheremployee.empname == this.empname && otheremployee.managerKin == this.managerKin);

    //}
    public override bool Equals(object obj)   //When Running this entire code, put a break-point on both the Equals() and GetHashCode() methods, and see the execution flow.
    {
        employee otheremployee;
        otheremployee = (employee)obj;
        return (obj.GetHashCode() == otheremployee.GetHashCode());

    }
    public override int GetHashCode()    //When Running this entire code, put a break-point on both the Equals() and GetHashCode() methods, and see the execution flow.
    {
        //int temp = base.GetHashCode(); // DONT USE THIS
        //return base.GetHashCode();
        int temp = empname.GetHashCode() + location.GetHashCode() + kinid.GetHashCode() + managerKin.GetHashCode();
        return temp;
    }
}

public class manager
{
    public string managername { get; set; }
    public double kinid { get; set; }



    public override int GetHashCode()
    {
        return base.GetHashCode();
    }
    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }
}
public class program
{
    public static void Main()
    {
        employee emp = new employee();
        employee emp2 = new employee();
        manager mng = new manager();
        manager mng2 = new manager();

        emp.empname = "Deepak";
        emp.location = "Pune";
        emp.kinid = 36885;
        emp.managerKin = 007;


        emp2.empname = "Astha";
        emp2.location = "Pune";
        emp2.kinid = 30000;
        emp2.managerKin = 001;

        mng.kinid = 007;
        mng.managername = "Gaurav";
        mng2.kinid = 001;
        mng2.managername = "Surya";

        Dictionary<employee, manager> relations = new Dictionary<employee, manager>();
        relations.Add(emp, mng); // put a BreakPoint here and see the execution flow
        relations.Add(emp2, mng2);// put a BreakPoint here and see the execution flow

        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine("The Employee details are :");
        foreach (var element in relations)
            Console.WriteLine(" \n Employee Name : {0} \n Location : {1} \n Employee KinId : {2} \n Manager's KinId : {3} ",
                element.Key.empname, element.Key.location, element.Key.kinid, element.Key.managerKin);

        Console.WriteLine("Enter the details of the Employee..");
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.Write("\nEmployee Name : "); string ename = Console.ReadLine();
        Console.Write("Location : "); string elocn = Console.ReadLine();
        Console.Write("Employee KinId : "); double ekinid = Convert.ToDouble(Console.ReadLine());
        Console.Write("Manager's ID : "); double emngr = Convert.ToDouble(Console.ReadLine());
        employee emp1 = new employee();
        emp1.empname = ename;
        emp1.location = elocn;
        emp1.kinid = ekinid;
        emp1.managerKin = emngr;


        int i = 0; // This variable acts as a indicator to find whether the Employee Key exists or not.
        if (relations.ContainsKey(emp1)) //Put a break point here and see the execution flow.
        {
            Console.WriteLine("the Employee : {0} exists..", emp1.empname);
            Console.WriteLine("the Employee reports to the following manager : {0} \n and the Manager's KinId is {1}.", (relations[emp1]).managername, relations[emp1].kinid);
            i = 1;
            Console.ReadLine();
        }

        if (i == 0)
        {
            Console.WriteLine("the details of the employee named {0} does not exist !!", emp1.empname);
            Console.ReadLine();
        }

#endregion

这篇关于GetHashCode的和等于实施字典C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆