C# class definition HELP



这是一个我似乎无法回答的项目问题

using System;
namespace ConsoleApplication2
{
    internal class Equipment : IComparable
    {
        private readonly string type;
        private readonly int serialNo;
        private string colour;
        public decimal cost;
        public Equipment(string type, int serialNo)
        {
            this.type = type == null ? "" : type.Trim();
            this.serialNo = serialNo;
        }
        public string Key
        {
            get { return type + ":" + serialNo; }
        }
        int IComparable.CompareTo(object obj)
        {
            return 0;
        }
    }
}

(a)重写适当的方法,以确保代表相同装备项目的类的不同实例在系统中被认为是相同的。

(b)重写适当的方法,使该类的实例能够在哈希表

中按键存储(和查找)。

你应该重写Equals和GetHashCode方法。

  1. 用适当的比较逻辑覆盖Equals()
  2. 覆盖GetHashCode(),参见c#
  3. 中的GetHashCode指南

必须在执行此任务之前开始读取此内容为什么在c#中重写Equals方法时重写GetHashCode很重要?

手动编写GetHashCode不是那么容易。总之,这是ReSharper为此目的生成的代码。这是一个完整的解决方案。(当然,它应该包含在类定义中)。但如果有人问你,你会怎么说——为什么会这样?这可能会很尴尬。

因此,除了其他人建议您阅读的GetHashCodeEquals之外,您还可以查找http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx以及http://msdn.microsoft.com/en-us/library/a569z7k8(v=VS.100).aspx

至于GetHashCode中397背后的奥秘,看看StackOverflow上的这个问题:为什么是'397'用于ReSharper GetHashCode重载?

        public bool Equals(Equipment other)
        {
            if (ReferenceEquals(null, other))
            {
                return false;
            }
            if (ReferenceEquals(this, other))
            {
                return true;
            }
            return Equals(other.colour, colour) && other.cost == cost && other.serialNo == serialNo && Equals(other.type, type);
        }
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }
            if (ReferenceEquals(this, obj))
            {
                return true;
            }
            if (obj.GetType() != typeof (Equipment))
            {
                return false;
            }
            return Equals((Equipment) obj);
        }
// note: if "Override the appropriate method to enable instances of this class
// to be stored (and found) by key in a hash table" is supposed to mean that only type and
// serialNo should be taken into account (since they are used to generate
// the Key value) - just remove the lines with cost and colour
        public override int GetHashCode()
        {
            unchecked
            {
                int result = (colour != null ? colour.GetHashCode() : 0);
                result = (result*397) ^ cost.GetHashCode();
                result = (result*397) ^ serialNo;
                result = (result*397) ^ (type != null ? type.GetHashCode() : 0);
                return result;
            }
        }

最新更新