Comparing object used as Key in Dictionary

前端 未结 3 948
一向
一向 2020-12-10 11:11

my class:

public class myClass
{
    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }
    public int D { get; set; }
         


        
3条回答
  •  长情又很酷
    2020-12-10 11:43

    By default, comparison puts objects into buckets based on their hash code. A detailed comparison is then performed (by calling Equals) if two hash codes are the same. If your class neither provides GetHashCode or implements equality, the default object.GetHashCode will be used--in which case nothing specific to your class will be used for value comparison semantics. Only the same reference will be found. If you don't want this, implement GetHashCode and implement equality.

    For example:

    public class myClass
    {
        public int A { get; set; }
        public int B { get; set; }
        public int C { get; set; }
        public int D { get; set; }
    
        public bool Equals(myClass other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return other.A == A && other.B == B && other.C == C && other.D == D;
        }
    
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof (myClass)) return false;
            return Equals((myClass) obj);
        }
    
        public override int GetHashCode()
        {
            unchecked
            {
                int result = A;
                result = (result*397) ^ B;
                result = (result*397) ^ C;
                result = (result*397) ^ D;
                return result;
            }
        }
    }
    

提交回复
热议问题