Options for uniquely identifying objects at runtime?

前端 未结 4 459
死守一世寂寞
死守一世寂寞 2021-01-03 05:45

I need to attach a unique identifier to objects at runtime. The identifier must be unique for the duration of the application. I plan to do this my having a private member

4条回答
  •  余生分开走
    2021-01-03 06:22

    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.

提交回复
热议问题