爲了進行單元測試,我經常必須重寫Equals
和GetHashCode
方法。在此之後我的課開始是這樣的:有沒有辦法在Equals和GetHashCode中減少樣板代碼的數量?
public class TestItem
{
public bool BoolValue { get; set; }
public DateTime DateTimeValue { get; set; }
public double DoubleValue { get; set; }
public long LongValue { get; set; }
public string StringValue { get; set; }
public SomeEnumType EnumValue { get; set; }
public decimal? NullableDecimal { get; set; }
public override bool Equals(object obj)
{
var other = obj as TestItem;
if (other == null)
{
return false;
}
if (object.ReferenceEquals(this, other))
{
return true;
}
return this.BoolValue == other.BoolValue
&& this.DateTimeValue == other.DateTimeValue
&& this.DoubleValue == other.DoubleValue // that's not a good way, but it's ok for demo
&& this.EnumValue == other.EnumValue
&& this.LongValue == other.LongValue
&& this.StringValue == other.StringValue
&& this.EnumValue == other.EnumValue
&& this.NullableDecimal == other.NullableDecimal;
}
public override int GetHashCode()
{
return this.BoolValue.GetHashCode()
^this.DateTimeValue.GetHashCode()
^this.DoubleValue.GetHashCode()
^this.EnumValue.GetHashCode()
^this.LongValue.GetHashCode()
^this.NullableDecimal.GetHashCode()
^(this.StringValue != null ? this.StringValue.GetHashCode() : 0);
}
}
雖然它不是很難做到這一點,一次又一次它很無聊而且容易出錯保持Equals
和GetHashCode
相同的字段列表。有沒有什麼方法可以列出只用於平等檢查和散列碼函數的filelds? Equals和GetHashCode應該根據這個設置列表來實現。
在我的想象的配置和這樣的設置列表的使用可能看起來像
public class TestItem
{
// same properties as before
private static readonly EqualityFieldsSetup Setup = new EqualityFieldsSetup<TestItem>()
.Add(o => o.BoolValue)
.Add(o => o.DateTimeValue)
// ... and so on
// or even .Add(o => o.SomeFunction())
public override bool Equals(object obj)
{
return Setup.Equals(this, obj);
}
public override int GetHashCode()
{
return Setup.GetHashCode(this);
}
}
有自動在Java中實現hashCode
和equals
,project lombok例如一種方式。我不知道是否有任何東西可以用來減少C#提供的樣板代碼。
用適當的對象狀態表示覆蓋tostring,其hashcode將基於該輸入。 – terrybozzio
@terrybozzio'ToString()'比較?永遠不要這樣做。首先,這是昂貴的。比較功能應該很快。其次,它甚至沒有砍掉樣板,它只是把它移到其他地方。 –
@Mike:我懷疑它。你上面的GetHashCode的實現非常具體。我可能完全不滿意這個實現。與Equals相同(在較小程度上)。 –