GetHashCode 实现使用元组派生 class
GetHashCode implementation using tuples for derived class
我喜欢使用元组实现 GetHashCode,如此处所述https://intellitect.com/overidingobjectusingtuple/。但是,这似乎不适用于派生 class。例如:
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();
}
不清楚我将如何使用元组实现 Derived GetHashCode。有什么建议么?我们目前正在这样做,但我很想摆脱未检查和散列常量:
public override int GetHashCode()
{
unchecked
{
return (base.GetHashCode() * HashCodeConstant) ^ (Prop3, Prop4).GetHashCode();
}
}
见https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0070
public override int GetHashCode()
{
return System.HashCode.Combine(base.GetHashCode(), Prop3, Prop4);
}
我喜欢使用元组实现 GetHashCode,如此处所述https://intellitect.com/overidingobjectusingtuple/。但是,这似乎不适用于派生 class。例如:
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();
}
不清楚我将如何使用元组实现 Derived GetHashCode。有什么建议么?我们目前正在这样做,但我很想摆脱未检查和散列常量:
public override int GetHashCode()
{
unchecked
{
return (base.GetHashCode() * HashCodeConstant) ^ (Prop3, Prop4).GetHashCode();
}
}
见https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0070
public override int GetHashCode()
{
return System.HashCode.Combine(base.GetHashCode(), Prop3, Prop4);
}