是否可以将对象用作 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/