本文介绍了GetHashCode()中引用的非只读字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从重载概念开始,我重载了方法 Equals GetHashCode

Started with overriding concepts and I override the methods Equals and GetHashCode.

主要是我想出了这个非常简单的代码:

Primarily I came up with this "very simple code":

internal class Person
    {
        public string name;

        public int age;

        public string lname;

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

        public override bool Equals(object obj)
        {
            var person = obj as Person;
            if (person != null)
            {
                return person.age == this.age && person.name == this.name && person.lname == this.lname;
            }

            return false;
        }

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

虽然效果很好,但我的共同开发者 Resharper先生给了我一些建议:

While this works great, my "co-developer" Mr.Resharper gave me some suggestions:


  1. GetHashCode()中引用的非只读字段。建议在以下代码行中出现:

  1. Non-readonly fields referenced in GetHashCode(). Suggestions came in this line of code:

返回this.age.GetHashCode()* this.name。 GetHashCode()* this.lname.GetHashCode();


  1. 应该我们仅对属性使用GetHashCode?

  1. Should we use GetHashCode only for Properties?


推荐答案

总结在注释:

散列的目的是为给定对象提供一个不变的值,无论发生什么变化-因此最好仅依赖于只读

Hashing is designed to provide a value that doesn't change for a given object, no matter what happens to it - hence it's best to depend only on readonly fields in your GetHashCode method.

首先,我建议使用 name lname 字段为只读,因为在您的使用情况下它们可能不会更改。

Firstly, I would suggest making the name and lname field readonly, because they probably don't change in your usage scenario.

对于年龄,它会定期更改,因此最好将 DateTime 存储为生日,该日期永远不会更改。然后,您也可以将其设为只读。

As for age, this is something that changes regularly, so probably best to store a DateTime for date of birth, which never changes. Then you can make that readonly too.

这篇关于GetHashCode()中引用的非只读字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:49