如何为JObject创建唯一的哈希码? [英] How can I create a unique hashcode for a JObject?

查看:64
本文介绍了如何为JObject创建唯一的哈希码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为JObjects实现缓存.

I'm trying to implement a cache for JObjects.

令我惊讶的是,他们没有重写GetHashCode方法,因此,我不能将其用作唯一键.

I was surprised to see that they didn't override the GetHashCode method and therefore, I can't use it as a unique key.

由于我的json很大,所以我不想使用JObject.ToString().GetHashCode作为解决方案.

Since my json's are pretty large, I don't want to use JObject.ToString().GetHashCode as a solution.

我确实看到它们有一个称为GetDeepHashCode的内部方法,但是该实现基于其他受保护的属性,因此,我无法复制"代码并从中创建扩展方法.

I did see that they have an internal method called GetDeepHashCode but the implementation is based on other protected properties and therefore, I cannot "copy" the code and create an extension method from it.

我也不想使用反射并调用内部的GetDeepHashCode方法.

I also don't want to use reflection and invoke the internal GetDeepHashCode method.

我正在寻找一种为JObject创建唯一的缓存键的方法,并且我不希望这种方法在性能方面会变得更加昂贵.

I'm looking for a way to create a unique cache key for a JObject and I don't want the method to be extra expensive when it comes to performance.

推荐答案

您可以使用 JTokenEqualityComparer.GetHashCode(JToken token) .它提供对您看到的GetDeepHashCode()方法的访问.

You can use JTokenEqualityComparer.GetHashCode(JToken token) for this purpose. It provides access to the GetDeepHashCode() method you saw.

var obj = JToken.Parse(jsonString);
var comparer = new JTokenEqualityComparer();
var hashCode = comparer.GetHashCode(obj);

请注意, JTokenEqualityComparer.Equals(JToken x, JToken y) 调用

Note that JTokenEqualityComparer.Equals(JToken x, JToken y) calls JToken.DeepEquals() (source) so this comparer is suited for use as an IEqualityComparer<JToken> when constructing hash tables or dictionaries of LINQ-to-JSON objects and uniqueness of values is desired.

这篇关于如何为JObject创建唯一的哈希码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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