C#如何从对象引用中计算哈希码 [英] C# how to calculate hashcode from an object reference

查看:328
本文介绍了C#如何从对象引用中计算哈希码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计,这对您来说是一个棘手的问题!

Folks, here's a thorny problem for you!

TickZoom系统的一部分必须将每种类型的对象的实例收集为Dictionary<>类型.

A part of the TickZoom system must collect instances of every type of object into a Dictionary<> type.

必须确保它们的相等性和哈希码基于对象的实例,这意味着引用相等而不是值相等.挑战在于,系统中的某些对象已覆盖Equals()和GetHashCode()以用作值相等性,并且它们的内部值会随着时间而变化.这意味着它们的Equals和GetHashCode是无用的.如何一般性地而不是侵入性地解决这个问题?

It is imperative that their equality and hash code be based on the instance of the object which means reference equality instead of value equality. The challenge is that some of the objects in the system have overridden Equals() and GetHashCode() for use as value equality and their internal values will change over time. That means that their Equals and GetHashCode are useless. How to solve this generically rather than intrusively?

到目前为止,我们创建了一个结构来包装每个称为ObjectHandle的对象,以将其散列到Dictionary中.正如您在下面看到的那样,我们实现了Equals(),但是仍然存在如何计算哈希码的问题.

So far, We created a struct to wrap each object called ObjectHandle for hashing into the Dictionary. As you see below we implemented Equals() but the problem of how to calculate a hash code remains.

public struct ObjectHandle : IEquatable<ObjectHandle>{
    public object Object;
    public bool Equals(ObjectHandle other) {
        return object.ReferenceEquals(this.Object,other.Object);
    }
}

看到了吗?有一个方法object.ReferenceEquals()可以比较引用相等性,而不考虑对象中任何重写的Equals()实现.

See? There is the method object.ReferenceEquals() which will compare reference equality without regard for any overridden Equals() implementation in the object.

现在,如何只考虑引用而不考虑任何重写的GetHashCode()方法来计算匹配的GetHashCode()?

Now, how to calculate a matching GetHashCode() by only considering the reference without concern for any overridden GetHashCode() method?

啊,我希望这能给您一个有趣的难题.我们被困在这里.

Ahh, I hope this give you an interesting puzzle. We're stuck over here.

此致, 韦恩

推荐答案

RuntimeHelpers. GetHashCode()正是在这里完成所需的工作.

RuntimeHelpers.GetHashCode() does exactly what is needed here.

这篇关于C#如何从对象引用中计算哈希码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆