【发布时间】:2010-10-19 13:17:18
【问题描述】:
有没有办法获取实例的唯一标识符?
GetHashCode() 对于指向同一个实例的两个引用是相同的。但是,两个不同的实例可以(很容易)获得相同的哈希码:
Hashtable hashCodesSeen = new Hashtable();
LinkedList<object> l = new LinkedList<object>();
int n = 0;
while (true)
{
object o = new object();
// Remember objects so that they don't get collected.
// This does not make any difference though :(
l.AddFirst(o);
int hashCode = o.GetHashCode();
n++;
if (hashCodesSeen.ContainsKey(hashCode))
{
// Same hashCode seen twice for DIFFERENT objects (n is as low as 5322).
Console.WriteLine("Hashcode seen twice: " + n + " (" + hashCode + ")");
break;
}
hashCodesSeen.Add(hashCode, null);
}
我正在编写一个调试插件,我需要获取某种 ID 用于在程序运行期间唯一的引用。
我已经设法获得了实例的内部地址,它在垃圾收集器 (GC) 压缩堆之前是唯一的(= 移动对象 = 更改地址)。
堆栈溢出问题Default implementation for Object.GetHashCode() 可能是相关的。
对象不在我的控制之下,因为我正在使用调试器 API 访问正在调试的程序中的对象。如果我可以控制这些对象,添加我自己的唯一标识符将是微不足道的。
我想要用于构建哈希表 ID -> 对象的唯一 ID,以便能够查找已经看到的对象。现在我这样解决了:
Build a hashtable: 'hashCode' -> (list of objects with hash code == 'hashCode')
Find if object seen(o) {
candidates = hashtable[o.GetHashCode()] // Objects with the same hashCode.
If no candidates, the object is new
If some candidates, compare their addresses to o.Address
If no address is equal (the hash code was just a coincidence) -> o is new
If some address equal, o already seen
}
【问题讨论】:
标签: c# unique hashcode gethashcode