How to tell the difference between two different b

2019-08-22 02:34发布

问题:

I am in a situation where I need need to keep track of all the variables a object, and therefore I need a way to

So I need a way to get a unique id (string or int, doesn't matter) that represent a object.

string obj1 = "test";
string obj2 = "test";

In this example obj1.id must be different from obj2.id. So obj.GetHashCode() is not what I am looking for...

I am considering using the pointer as an identifier like this:

GCHandle handle = GCHandle.Alloc(obj1 , GCHandleType.WeakTrackResurrection);
int obj1Id = GCHandle.ToIntPtr(handle).ToInt32();

But I don't know if that is a good idea, maybe it can change, if it gets moved in memory (don't know if that ever happens though). My gut tells me it's not a good solution... Or is it fine and safe to do it that way?

Or is there another way to get a unique identifier?