我讀到this question here,這導致我this article here。我可以實現一個基本的GetHashCode(),它可以用於我的抽象基類的所有擴展?
我有一個抽象的基類,允許我限制方法只接受我的類擴展我的抽象基類(基本多態性)。我的問題是:我可以在抽象基類中實現GetHashCode()
以爲任何具體實現提供合適的重寫嗎? (即以避免在每個具體類中重寫GetHashCode()
。)
我想象在我的抽象基類,像這樣的方法:
public abstract class FooBase
{
private static readonly int prime_seed = 13;
private static readonly int prime_factor = 7;
public override int GetHashCode()
{
// Seed using the hashcode for this concrete class' Type so
// two classes with the same properties return different hashes.
int hash = prime_seed * this.GetType().GetHashCode();
// Get this concrete class' public properties.
var props = this.GetType().GetProperties(BindingFlags.Public);
foreach (var prop in props)
{
// Factor in each of this concrete class' public properties' hashcodes.
hash = (hash * prime_factor) + prop.GetHashCode();
}
return hash;
}
}
這似乎在一些基本的平等單元測試,但我的工作覺得我忽略了一些東西。我仍然需要在每個具體類中提供一個覆蓋,以避免編譯器警告不要覆蓋GetHashCode(),但至少這樣我不必爲每個實現手動編寫實現。
好像它會很慢涉及反射散列 –
接下來,我去了並做了一些關於GetHashCode()和Equals()及其相互關係的實現和使用的更多閱讀。在獲得更好的理解之後,我放棄了上面正在處理的基礎GetHashCode()。排隊其中一箇舊的NBC PSA:更多你知道...... – JMD
重寫'structs'中的'GetHashCode()'總是好的原因之一就是避免使用與此相同的一般思想的默認值。它大部分時間都在使用,但是它比大多數簡單的'GetHashCode()'重寫要慢很多,你可以在一分鐘之內編寫代碼。 –