c# - 如何使用对象的标识作为 Dictionary<K,V> 的键

标签 c# .net

是否可以将对象用作 Dictonary<object, ...> 的键?以这样一种方式,只有当对象相同时,字典才会将对象视为相等?

例如,在下面的代码中,我希望第 2 行返回 11 而不是 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 中是否有这样的字典,还是我必须从头开始实现它?

最佳答案

您不需要构建自己的字典 - 您需要构建自己的 IEqualityComparer<T> 实现它使用身份进行散列和相等。我认为框架中不存在这样的东西,但由于 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成为一个引用类型,这样你最终会在字典中找到对象;如果你将它用于值类型,你可能会得到一些奇怪的结果。 (我不知道它是如何工作的;我怀疑它不会。)

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

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

关于c# - 如何使用对象的标识作为 Dictionary<K,V> 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8946790/

相关文章:

.net - 如何在 WPF 中显示“IntelliSense Babel 图标”?

c# - 如何将报表查看器语言设置为与 CultureInfo.CurrentUICulture 相同?

c# - 使用接口(interface)参数指定方法

c# - 连接字符串时处理 LINQ 中的空列

c# - XNA 4.0 + DirectX 9?

c# - 独立动态表单编辑器 + 序列化 + C# 本地化

c# - StringFormat 在设计器中显示错误,但在编译后不显示

c# - C#编译器会优化这段代码吗?

c# - 使用套接字的最快下载形式

c# - 在调用 ShowDialog 之后/期间使用异步值更新 ViewModel