我读到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()'重写要慢很多,你可以在一分钟之内编写代码。 –