Options for uniquely identifying objects at runtime?

元气小坏坏 提交于 2019-11-30 14:52:31

I would recommend using an integer value, and auto-incrementing it on assignment. You could use Interlocked.Increment to make this operation thread safe.

Most likely, a 32bit integer will be large enough for this task. I would recommend something like:

private static newObjectId = int.MinValue;

private static int GetNextId()
{
    return Interlocked.Increment(ref newObjectId);
}

You can then use that in your base class for assigning a new, unique identifier.

To generate unique ids for objects you could use the aptly named ObjectIDGenerator that we conveniently provide for you:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.objectidgenerator.aspx

Note that, as the comment points out, the object id generator keeps a reference to the object alive, so it is only suitable for objects that you know are going to survive the life of the application anyway. If you intend to use this thing on more ephemeral objects then it is not a good solution.

You could build your own object ID generator that kept weak references if you wanted; it wouldn't be that difficult.

Do you need the identifier to be unique across all objects or just within a specific type?

You have a couple of options:

  1. If you aren't overriding Object.GetHashCode(), this will give you a pretty (but not 100%) reliable identifier. Note, though, that (per the docs), this is not guaranteed to be unique. Your chances of hitting a duplicate, though, are pretty low.
  2. If you are (or need 100%), the simplest solution would be to use a private static long lastObjectId in your class. Within the base constructor, use Interlocked.Increment(ref lasObjectId) as the value for the current object.
  3. If you need the identifier to be unique across objects, you can do something similar to 2., but you'll have to use a central class to manage these ID's.

If the uniqueness is just for the life of the application, can't you use a 32-bit integer, initialized to zero, and then simply incremented with each object allocation?

There's no need to worry about TickCount or anything like that. The number "2" is unique among numbers; it's as different from "1" and "3" as it is from "1,203,718" if all you're testing for is equality.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!