编程语言
首页 > 编程语言> > C#中重写Equals和GetHashCode方法的案例

C#中重写Equals和GetHashCode方法的案例

作者:互联网

C#中重写Equals和GetHashCode方法的一些案例:

class keyClass
{
    public string Name { get; set; }
    public string Code { get; set; }
    public override bool Equals(object obj)
    {
        if (null == obj)
            return false;
        if (obj.GetType() != this.GetType())
            return false;
        return ((keyClass)obj).Name.Equals(this.Name);
    }
    public override int GetHashCode()
    {
        return this.Code.GetHashCode();
    }
    public static bool operator ==(keyClass o1, keyClass o2)
    {
        if (o1 is null)
        {
            return o2 is null;
        }
        else
        {
            return o1.Equals(o2);
        }
    }

    public static bool operator !=(keyClass o1, keyClass o2)
    {
        return !(o1 == o2);
    }
}

 在将对象当做键时,会先执行GetHashCode方法。

标签:keyClass,return,C#,Equals,GetHashCode,public,o1
来源: https://www.cnblogs.com/east115/p/16247973.html