我应该怎么做才能拥有正确的重写 equals 和 hashcode 方法?

问题描述 投票:0回答:0

我下面有课

using System;
using System.Collections.Generic;

namespace x
{
    public class y : IEquatable<y>
    {

        public int a;
        public int b;

        public override bool Equals(object obj)
        {
            return Equals(obj as y);
        }

        public bool Equals(y other)
        {
            return other != null &&
                   a == other.a &&
                   b == other.b &&
        }
        public override int GetHashCode()
        {
            int hashCode = 1557084561;
            hashCode = hashCode * -1521134295 + 
            EqualityComparer<string>.Default.GetHashCode(Name);
            hashCode = hashCode * -1521134295 + a.GetHashCode();
            hashCode = hashCode * -1521134295 + b.GetHashCode();
            return hashCode;
        }
    }
}

我的问题是方法

public override int GetHashCode()
是否应该对应于方法
public bool Equals(y other)
而不是
Equals(object obj)
?我怎么知道。如果是这样,我如何对应它,因为我无法创建方法
public bool override Equals(y other)

c# equals hashcode
© www.soinside.com 2019 - 2024. All rights reserved.