C#类定义帮助

时间:2011-08-15 12:31:16

标签: c#

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

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)覆盖适当的方法o确保代表同一设备项的类的不同实例在系统中被认为是相同的。

(b)覆盖适当的方法,以便通过哈希表中的键存储(和找到)此类的实例

3 个答案:

答案 0 :(得分:3)

您应该为此目的覆盖Equals和GetHashCode方法。

答案 1 :(得分:1)

  1. 使用适当的比较逻辑覆盖Equals()
  2. 覆盖GetHashCode(),请参阅GetHashCode Guidelines in C#
  3. 必须在执行此类任务之前开始阅读此内容 Why is it important to override GetHashCode when Equals method is overriden in C#?

答案 2 :(得分:0)

手动编写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上查看此问题:Why is '397' used for ReSharper GetHashCode override?

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