最佳答案
有什么办法可以得到唯一标识符的实例吗?
对于指向同一实例的两个引用,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 作为引用,这在程序运行期间是唯一的。
我已经设法获得了实例的内部 ADDRESS,这是唯一的,直到垃圾收集器(GC)压缩堆(= 移动对象 = 更改地址)。
堆栈溢出问题 对象的默认实现。 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
}