简体   繁体   中英

GetHashCode implementation using tuples for derived class

I like to implement GetHashCode using tuples, as described here https://intellitect.com/overidingobjectusingtuple/ . However, this doesn't seem to work for a derived class. For example:

class Base
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }

    public override int GetHashCode() => (Prop1, Prop2).GetHashCode();
}

class Derived : Base
{
    public int Prop3 { get; set; }
    public int Prop4 { get; set; }

    public override int GetHashCode() => (Prop3, Prop4, ???).GetHashCode();
}

It's unclear how I'd implement the Derived GetHashCode using a tuple. Any suggestions? We're currently doing it this way, but I'd love to get rid of the unchecked and hash constant:

public override int GetHashCode()
{
    unchecked
    {
        return (base.GetHashCode() * HashCodeConstant) ^ (Prop3, Prop4).GetHashCode();
    }
}

see https://learn.microsoft.com/en-us/do.net/fundamentals/code-analysis/style-rules/ide0070

public override int GetHashCode()
{
    return System.HashCode.Combine(base.GetHashCode(), Prop3, Prop4);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM