如何使用对象的身份作为Dictionary< K,V>的键。 [英] How to use an object's identity as key for Dictionary<K,V>

查看:90
本文介绍了如何使用对象的身份作为Dictionary< K,V>的键。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将对象用作字典<...,...> 的键,以使词典仅在以下情况下将对象视为相等它们是相同的吗?

Is it possible to use an object as a key for a Dictonary<object, ...> in such a way that the Dictionary treats objects as equal only if they are identical?

例如,在下面的代码中,我希望第2行返回11而不是12:

For example, in the code below, I want Line 2 to return 11 instead of 12:

Dictionary<object, int> dict = new Dictionary<object, int>();
object a = new Uri("http://www.google.com");
object b = new Uri("http://www.google.com");

dict[a] = 11;
dict[b] = 12;

Console.WriteLine(a == b);  // Line 1. Returns False, because a and b are different objects.
Console.WriteLine(dict[a]); // Line 2. Returns 12
Console.WriteLine(dict[b]); // Line 3. Returns 12

当前的Dictionary实现使用 object.Equals () object.GetHashCode();但是我正在寻找另一种类型的字典,该字典使用对象的 identity 作为键(而不是对象的值)。 .NET中是否有这样的词典?还是我必须从头开始实现它?

The current Dictionary implementation uses object.Equals() and object.GetHashCode() on the keys; but I am looking for a different kind of dictionary that uses the object's identity as a key (instead of the object's value). Is there such a Dictionary in .NET or do I have to implement it from scratch?

推荐答案

您不需要构建您自己的字典-您需要构建自己的 IEqualityComparer< T> 实现,该实现将身份用于哈希和相等性。我不认为框架中存在这样的东西,但是由于 RuntimeHelpers.GetHashCode

You don't need to build your own dictionary - you need to build your own implementation of IEqualityComparer<T> which uses identity for both hashing and equality. I don't think such a thing exists in the framework, but it's easy enough to build due to RuntimeHelpers.GetHashCode.

public sealed class IdentityEqualityComparer<T> : IEqualityComparer<T>
    where T : class
{
    public int GetHashCode(T value)
    {
        return RuntimeHelpers.GetHashCode(value);
    }

    public bool Equals(T left, T right)
    {
        return left == right; // Reference identity comparison
    }
}

我已限制 T 作为引用类型,这样您将在字典中得到 objects ;如果将其用于值类型,则可能会得到一些奇怪的结果。 (我不知道该如何工作;我怀疑不会。)

I've restricted T to be a reference type so that you'll end up with objects in the dictionary; if you used this for value types you could get some odd results. (I don't know offhand how that would work; I suspect it wouldn't.)

有了这些,剩下的就是简单。例如:

With that in place, the rest is easy. For example:

Dictionary<string, int> identityDictionary =
    new Dictionary<string, int>(new IdentityEqualityComparer<string>());

这篇关于如何使用对象的身份作为Dictionary&lt; K,V&gt;的键。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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