如何打印对象ID? [英] How to print object ID?

查看:63
本文介绍了如何打印对象ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

`我需要知道来自程序完全不同部分的两个引用是否引用同一对象。
我不能以编程方式比较引用,因为它们来自不同的上下文(一个引用在另一个上下文中不可见,反之亦然)。

`I need to know if two references from completely different parts of the program refers to the same object. I can not compare references programaticaly because they are from the different context (one reference is not visible from another and vice versa).

然后我要打印使用 Console.WriteLine()的每个对象的唯一标识符。但是 ToString()方法不会返回唯一标识符,而只会返回类名。

Then I want to print unique identifier for each object using Console.WriteLine(). But ToString() method doesn't return "unique" identifier, it just returns "classname".

是可以在C#中打印唯一标识符(例如Java)?

Is it possible to print unique identifier in C# (like in Java)?

推荐答案

您可以轻松获得最近的标识符(不会受GC等移动对象的影响)可能 RuntimeHelpers.GetHashCode(Object)。这给出了通过在对象上非虚拟地调用 Object.GetHashCode()将返回的 哈希码。不过,这仍然不是唯一标识符。它可能足以用于诊断目的,但您不应该依赖它进行生产比较。

The closest you can easily get (which won't be affected by the GC moving objects around etc) is probably RuntimeHelpers.GetHashCode(Object). This gives the hash code which would be returned by calling Object.GetHashCode() non-virtually on the object. This is still not a unique identifier though. It's probably good enough for diagnostic purposes, but you shouldn't rely on it for production comparisons.

编辑:如果这仅用于诊断,则可以添加一种规范化ID生成器,它只是一个 List< object> ...。当您请求一个对象的 ID时,您将检查该对象是否已存在于列表中(通过比较引用),然后将其添加到末尾(如果没有)。该ID将成为列表的索引。当然,在不引入内存泄漏的情况下执行此操作会涉及弱引用等,但是作为一个简单的技巧,这可能对您有用。

If this is just for diagnostics, you could add a sort of "canonicalizing ID generator" which was just a List<object>... when you ask for an object's "ID" you'd check whether it already existed in the list (by comparing references) and then add it to the end if it didn't. The ID would be the index into the list. Of course, doing this without introducing a memory leak would involve weak references etc, but as a simple hack this might work for you.

这篇关于如何打印对象ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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